【发布时间】:2019-09-01 15:14:53
【问题描述】:
我正在尝试从 URL 获取 JSON 数据,但它给了我一个错误(跨源请求被阻止:同源策略不允许读取位于 http://core.agricx.com/api/Apiagricx/get_config_test 的远程资源。(原因:CORS 标头 'Access-Control- Allow-Origin' 缺失)。
后端代码(节点js)
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
前端代码(dashboard.js)
fetch('https://core.agricx.com/api/Apiagricx/get_config_test', {
method: "GET",
credentials: "include",
cache: "no-cache"
})
.then(response => response.json())
.then(out => {
console.log("for out");
console.log(out);
})
.catch(err => {
console.log("for err");
console.error(err);
});
我希望您可以在直接输入 URL 时看到 JSON 数据输出。但是代码将进入 catch 块并阻止我从该 URL 获得的响应。
【问题讨论】:
-
请确保此后端中间件位于端点之前。
标签: javascript node.js