我有一个在端口 8002 上运行的 NodeJS/Express 后端 API 服务器和在端口 3000 上运行的 ReactJS 前端应用程序。
我正在从reactJS前端应用程序提交一个表单以发布到API服务器上,该服务器将其保存到数据库中。
我调用函数 saveAndContinue 来提交表单。
下面是执行此操作的代码片段:
class Confirmation extends Component{
saveAndContinue = (e) => {
e.preventDefault();
console.log("props : " + JSON.stringify(this.props.values));
var form_id = Math.floor(Math.random() * 1000000);
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
headers.append('Access-Control-Allow-Origin', '*');
fetch("http://localhost:8002/sharepoint/big_data_poc/" + form_id,{
method:'POST',
//mode: 'cors',
body:JSON.stringify(this.props.values),
headers: headers
}).then(res => res.json()).then(this.setState({confirmation_id:form_id}))
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));
this.props.nextStep();
}
我还将 Access-Control-Allow-Origin 添加到了 nodeJS 服务器响应 header
cb_service.prototype.addForm = function(req,res,form_id, doc_type,payload){
logger.info(JSON.stringify(payload));
bucket.upsert(form_id,payload,function(err,result){
if(err){
logger.error("error inserting data in couchbase")
}
else {
res.setHeader('Access-Control-Allow-Origin','*')
res.setHeader('Access-Control-Allow-Methods','POST, GET, OPTIONS, PUT')
res.setHeader('mode','cors')
logger.info("successful inserts");
res.status(200);
return res.json({"success":"ok"});
}
})
}
我根本没有看到任何请求进入服务器。我只是在浏览器控制台中看到以下错误:
Failed to load http://localhost:8002/sharepoint/big_data_poc/944960: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
非常感谢任何帮助!我想我已经完成了类似问题所建议的一切。甚至 Safari 也会抛出以下错误:
[Error] Failed to load resource: Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin. (408661, line 0)
[Error] Fetch API cannot load http://localhost:8002/sharepoint/big_data_poc/408661. Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin.
非常感谢!
最佳答案
安装cors
,你不会有任何问题const cors = require('cors'); app.use(cors());
npm 上的链接 https://www.npmjs.com/package/cors
关于javascript - 即使在服务器和客户端上设置 header 后,请求的资源上仍存在错误 "No ' Access-Control-Allow-Origin' header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54176878/