繁体   English   中英

Axios发布参数未发送

[英]Axios post params not being sent

我在React应用中使用Axios来访问api。 我正在尝试将登录详细信息发布到服务器,但是当我记录请求的正文时,我得到的只是{}

继承人的要求:

handleSubmit() {
    let email    = this.state.email
    let password = this.state.password

    request.post("/login",{email: email, password: password}) //just prints {} on the backend
    .then((results)=>console.log(results))
    .catch((err)=>console.log(err))
}  

如果我删除括号,并只是发送了一个像hello这样的字符串作为测试,我会返回{ hello: '' }因此很清楚它的工作原理。 在此阶段,我已经尝试了所有方法来获取用户的现场输入,但没有成功。

这是服务器代码:

var app = express();
var bodyParser = require("body-parser");

app.use(bodyParser.urlencoded({
    extended: true
}));
app.post("/login",(req,res) => {
    console.log(req.body);
})

我的api是使用express.js在端口4000上的节点服务器

更新 :必须将对象字符串化为querystring。 您可以为此使用qs包 请参阅更新的代码。

由于您使用的是body-parserbodyParser.urlencoded中间件,因此请求的content-type需要设置为'x-www-form-urlencoded'。

import qs from "qs";

// ...

handleFormSubmit = event => {
    event.preventDefault();

    const requestBody = {
      email: this.state.email,
      password: this.state.password
    }

    const config = {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    }

    request.post('/login', qs.stringify(requestBody), config)
    .then(res=>console.log(res))
    .catch(err=>console.log(err))
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM