该问题是由于浏览器的同源策略引起的。当使用axios发出跨域请求时,请求头中有一些不被允许的参数,因此服务器会返回一个CORS(跨域资源共享)错误。
我们可以通过以下方法解决这个问题:
1.在服务器端设置响应头,允许跨域请求。在响应头中添加"Access-Control-Allow-Origin"字段,值为"*"或具体的请求地址。
2.使用withCredentials选项将cookie等身份验证信息发送到跨域请求的服务器。这需要服务器在响应头中设置"Access-Control-Allow-Credentials"字段为true。
以下是一个示例代码:
// 在服务器端设置响应头
app.use(function(req, res, next) {
// 允许所有来源访问
res.header('Access-Control-Allow-Origin', '*');
// 允许发送cookie
res.header('Access-Control-Allow-Credentials', true);
// 其他响应头设置
...
next();
});
// axios post请求
axios.post('http://example.com', {
// 请求体
}, {
// 添加withCredentials选项
withCredentials: true
})
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});