-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.mjs
85 lines (69 loc) · 2.26 KB
/
server.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// // server.js
// import express from 'express';
// import fetch from 'node-fetch';
// import dotenv from 'dotenv';
// const SERVER_KEY = import.meta.env.VITE_SERVER_KEY ;
// dotenv.config();
// const app = express();
// const PORT = 3000;
// // Middleware para habilitar o CORS
// app.use((req, res, next) => {
// res.header('Access-Control-Allow-Origin', 'http://localhost:5175');
// res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
// res.header('Access-Control-Allow-Credentials', true);
// next();
// });
// app.use('/', async (req, res) => {
// try {
// const response = await fetch('https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest', {
// method: 'GET',
// headers: {
// 'X-CMC_PRO_API_KEY': SERVER_KEY,
// },
// });
// if (!response.ok) {
// throw new Error(`HTTP error! Status: ${response.status}`);
// }
// const json = await response.json();
// res.json(json);
// } catch (ex) {
// console.error('Error fetching data from CoinMarketCap API:', ex);
// res.status(500).json({ error: 'Internal Server Error' });
// }
// });
// app.listen(PORT, () => {
// console.log(`Server is running at http://localhost:${PORT}`);
// });
import fetch from 'node-fetch';
import express from 'express';
import dotenv from 'dotenv';
dotenv.config();
const app = express();
const PORT = 3000;
// Middleware para habilitar o CORS
app.use((req, res, next) => {
// ...
});
app.use('/', async (req, res) => {
try {
const response = await fetch('https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest', {
method: 'GET',
headers: {
'X-CMC_PRO_API_KEY': process.env.VITE_SERVER_KEY,
},
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const json = await response.json();
console.log(json);
res.json(json);
} catch (ex) {
console.error('Error fetching data from CoinMarketCap API:', ex);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});