我在 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 上的 Node 服务器
最佳答案
更新:该对象必须被字符串化为查询字符串。您可以使用qs package为了这个目的。查看更新后的代码。
由于您使用的是body-parser
的bodyParser.urlencoded
中间件,因此请求的内容类型需要设置为“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))
}
关于javascript - axios post params没有被发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54772894/