Node.js 不能';t从react应用程序调用节点api
我正在从运行在端口3000上的react应用程序向运行在端口8080上的节点api进行api调用。我得到的错误如下: 无法加载XMLHttpRequest。对飞行前请求的响应未通过访问控制检查:请求的资源上不存在“访问控制允许来源”标头。因此,不允许访问源“” 我的react api调用是:Node.js 不能';t从react应用程序调用节点api,node.js,api,reactjs,Node.js,Api,Reactjs,我正在从运行在端口3000上的react应用程序向运行在端口8080上的节点api进行api调用。我得到的错误如下: 无法加载XMLHttpRequest。对飞行前请求的响应未通过访问控制检查:请求的资源上不存在“访问控制允许来源”标头。因此,不允许访问源“” 我的react api调用是: export const addUser=(data) =>{ console.log(data); return function(dispatch,data){ axios.post('http:
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);
})
}
}
我的服务器端代码在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();
});
我仍然无法将数据发布到我的数据库。。任何建议都会对我很有帮助。谢谢。选项1:
npm install cors
var cors = require('cors');
app.use(cors());
选项2:
或者使用setHeader方法,而不是仅使用header
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();
});