【发布时间】:2020-07-21 07:54:28
【问题描述】:
我已经搜索了很多,但没有一个解决方案有效:无法通过 axios 发送内容类型。但是如果我使用邮递员拦截器并且这次我'发送' axios 生成的请求它可以工作:node.js / express 服务器正确接收请求并且正文解析器工作正常!
反应方:
const API_URL = "http://localhost:8800/auth/";
const headers = {
accept: 'application/json, text/plain, */*',
'content-type': 'application/json;charset=UTF-8'
};
class AuthService {
register(pseudo, email, password) {
return axios.post(API_URL + "signup/",
{ pseudo, email, password },
{ headers: headers})
.then(response => {
if (response.data.accessToken) {
localStorage.setItem("user", JSON.stringify(response.data));
}
return response.data;
});
}
服务器端
const app = express();
app.use(function (req, res, next) {
console.log( req.headers);
next();
});
app.use( bodyParser.urlencoded({ extended: true }), bodyParser.json());
【问题讨论】:
-
英语,请。
-
尝试使用CORS中间件
-
@DimitarVeljanovski — 这绝对没有帮助。需要 CORS 权限才能 (a) 设置内容类型标头(这是问题的内容)和 (b) 读取响应(问题中的代码正在执行的操作)。
-
"Cannot send content-type by axios" — 我测试了该代码,并且 content-type 设置正确(不是必须的,JSON 是 Axios 的默认设置)。我无法重现该问题。检查浏览器的控制台是否有错误消息。
-
对于昆汀:我只是在
const app = express();之后添加app.use(cors());,没有其他更改就可以了
标签: javascript reactjs axios