[英]Axios post params not being sent
I'm using Axios in a react app to acess an api. 我在React应用中使用Axios来访问api。 I'm trying to post login details to the server however when I log the body of the request all I get is
{}
. 我正在尝试将登录详细信息发布到服务器,但是当我记录请求的正文时,我得到的只是
{}
。
Heres the request: 继承人的要求:
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))
}
If I remove the braces and just sent a string like hello
as a test I get back { hello: '' }
so clearly its working. 如果我删除括号,并只是发送了一个像
hello
这样的字符串作为测试,我会返回{ hello: '' }
因此很清楚它的工作原理。 I've tried everything at this stage to get the user input in the field but have not been successful. 在此阶段,我已经尝试了所有方法来获取用户的现场输入,但没有成功。
Heres the server code: 这是服务器代码:
var app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({
extended: true
}));
app.post("/login",(req,res) => {
console.log(req.body);
})
My api is a node server on port 4000 using express.js 我的api是使用express.js在端口4000上的节点服务器
Update : The object has to be stringified as querystring. 更新 :必须将对象字符串化为querystring。 You can use qs package for that purpose.
您可以为此使用qs包 。 See the updated code.
请参阅更新的代码。
Since you are using body-parser
's bodyParser.urlencoded
middleware, request's content-type need to be set as 'x-www-form-urlencoded'. 由于您使用的是
body-parser
的bodyParser.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.