我使用 NodeJS 作为后端,使用 ReactJS 作为前端。
我请求 Axios 网络时遇到问题。我所有的 Get 请求都有效。但是Post请求不起作用。我只是遇到这个错误“网络错误”
我创建了一个简单的网络服务来向您展示我的问题:
//Serveur code
helloWs : (request:Express.Request, response:Express.Response) => {
try {
response.send('hello WS !')
} catch (error) {
console.error(error)
response.send('error' + error + 'status : ' + error.response.status)
response.end()
}
}
//Here I create my root
router.post('/helloWs',DocumentController.helloWs)
//This is my front
axios.post('http://localhost:9000/1/documents/helloWs', {
}) .catch(function (error) {
if (error.response) {
console.log('Error data : ', error.response.data);
console.log('Error status : ', error.response.status);
console.log('Error headers : ', error.response.headers);
} else if (error.request) {
console.log('Error request : ', error.request);
} else {
console.log('Error message : ', error.message);
}
console.log(error.config);
})
在导航器控制台中,我刚刚network error
,我的网络服务位于 OPTION 中,而不是“POST”中
我试图在 axios 中添加标头,但它不起作用。我指定我已经用邮递员测试过了,没问题。
你有好主意吗 ?
谢谢
这很可能是与 cors 相关的错误,浏览器在实际请求之前发出 OPTION 请求,以检查您的域是否有权访问该资源。
邮递员不执行预检请求,这就是您收到响应的原因
在定义路由之前尝试在服务器端代码中添加此中间件
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)