我有一个Node / React应用程序从API中提取数据 .
在服务器端( server.js ),我有一个“内部”URL,它从API中获取数据,然后将其作为JSON返回 . 像这样:
server.get('/api/data', (req, res) => {
Promise.resolve(getAPIData()).then(data => {
res.writeHead(200, {'Content-Type': 'application/json'})
return res.end(serialize(data))
}).catch((error) => {
console.log(error)
res.writeHead(200, {'Content-Type': 'application/json'})
return res.end(serialize({}))
})
})
然后在React(Next.js)的前端,我用 example.com/api/data URL获取这个JSON并在页面上显示它 .
我的问题是我想限制只能从我的域访问 example.com/api/data URL(在这种情况下,假设是example.com) . 我不希望 someotherdomain.com 能够从URL访问相同的数据 .
我安装了 helmet ,但这并不是我想要的 . CORS似乎也不是答案 .
有没有标准的方法来做到这一点?
Update :
const cors = require('cors')
...
const corsOptions = {
origin: (process.env.NODE_ENV === 'development') ? 'http://localhost:3000' : 'https://example.com',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
然后在路线上:
server.get('/api/data', cors(corsOptions), (req, res) => {
Promise.resolve(getAPIData()).then(data => {
res.writeHead(200, {'Content-Type': 'application/json'})
return res.end(serialize(data))
}).catch((error) => {
console.log(error)
res.writeHead(200, {'Content-Type': 'application/json'})
return res.end(serialize({}))
})
})