Axios发布空请求 [英] Axios posting empty request

查看:144
本文介绍了Axios发布空请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向后端发送axios请求,但是最终它有一个空的body,我不明白为什么这样做. 这是请求的代码:

I am trying to send an axios request to the backend, but it ends up having an empty body, and i do not understand why it does that. This is the code for the request:

axios.post('/register', {email: email, password: password, username: username, company: company}).then(response => {
    console.log(response.data);
});  

这是后端的代码:

authRouter.post('/register', (request, response) => {
    console.log(request.body);

});

这将输出一个空的request.body.我还检查了发送的JSON,它根本不是空的.有没有办法在发送之前查看请求的形式? 此authRoutermodule.export,正由主app模块使用.此app模块具有以下配置:

And this one outputs an empty request.body. I've also checked the JSON sent, and it is not empty at all. Is there a way to see what is the form of the request before being sent? This authRouter is a module.export, that is being used by the main app module. This app module has this configuration:

app.use(express.static("public"));
app.use(session({ secret: "shh", resave: false, saveUninitialized: false }));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(passport.initialize());
app.use(passport.session());

app.set('views', __dirname + '/views');
app.set('view engine', 'pug');

app.use(authRouter);

https.createServer({key: fs.readFileSync('ssl/key.pem'), cert: fs.readFileSync('ssl/cert.pem')}, app).listen(8080);

推荐答案

问题来自以下事实:body-parser需要一个x-www-form-urlencoded请求,而我没有提供请求.

The issue came from the fact that body-parser wants an x-www-form-urlencoded request, and I wasn't providing one.

我已经为其设置了axios请求的标头,代码如下:

I've set the header for the axios request to it, and the code looks like this:

axios.post('/register', {
  email: email,
  password: password,
  username: username,
  company: company
}, {
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})
  .then(response => {
    console.log(response.data);
  });

这篇关于Axios发布空请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆