[英]couldn't make node api call from react app
I am making a api call from react app running on port 3000 to node api running on port 8080.And i am getting error as: 我正在从端口3000上运行的react应用到端口8080上运行的节点api进行api调用,并且出现以下错误:
XMLHttpRequest cannot load http://localhost:8080/register . XMLHttpRequest无法加载http:// localhost:8080 / register 。 Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. 对预检请求的响应未通过访问控制检查:在所请求的资源上不存在“ Access-Control-Allow-Origin”标头。 Origin ' http://localhost:3000 ' is therefore not allowed access. 因此,不允许访问源' http:// localhost:3000 '。
My react api call is: 我的react api调用是:
export const addUser=(data) =>{
console.log(data);
return function(dispatch,data){
axios.post('http://localhost:8080/register',{
phone:data.phone,
password:data.password,
first_name:data.fname,
last_name:data.lname,
dob:data.dob,
gender:data.gender
})
.then(response =>{
console.log('data submitted successfully');
dispatch({
type : AddUser,
User : data
})
}).catch(err =>{
console.log(err);
})
}
}
And my server side code is in node.js and i included the headers as: 我的服务器端代码在node.js中,我将标头包括为:
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', "*");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
I still can't post my data to my database.. Any suggestion will really help me. 我仍然无法将数据发布到数据库中。任何建议都将对我有帮助。 Thanks. 谢谢。
Option 1: 选项1:
npm install cors
var cors = require('cors');
app.use(cors());
Option 2: Or Use setHeader Method instead of only header 选项2:或使用setHeader方法而不是仅标头
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.