gpt4 book ai didi

javascript - 通过 Fetch Api 发布请求时 Req.body 未定义

转载 作者:行者123 更新时间:2023-12-05 01:37:09 25 4
gpt4 key购买 nike

当我尝试通过在 body 中传递参数来通过 fetch 方法调用 POST Api 时,我在后端端(Node js 端)得到了 req.body undefined。另外,当我通过传递参数通过 Postman 调用相同的 POST api 时在 body 然后它成功工作(我得到了 req.body)。后端在 node js 中,前端在 React js 中。任何帮助将不胜感激。

Node Backend log Browser console log Network console in browser Network console  in browser


import React, { Component } from 'react'
import '../Css/Login.css'

export class Login extends Component {

constructor(props) {
super(props)

this.state = {
name: "",
password: ""
}

this.onChange = this.onChange.bind(this);
}

submitHandler = (e) => {
e.preventDefault();
console.log(this.state);
try {

let result = fetch('http://localhost:4000/users/login', {
method: 'POST',
mode: 'no-cors',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'

},
body: { name: this.state.name, password: this.state.password }
})

result.then((sucess) => { console.log(sucess) })
} catch (error) {
console.log(error)

}



}

onChange(e) {
this.setState({ [e.target.name]: e.target.value })

}
render() {
return (
<div>
<div className="LoginPage">
<div class="container Login_div">
<div className="Admin_panel"><h2>Admin Panel</h2></div>

<form onSubmit={this.submitHandler}>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" name="name" class="form-control" placeholder="Enter email" onChange={this.onChange} />
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" name="password" class="form-control" placeholder="Enter password" onChange={this.onChange} />
</div>

<button type="submit" class="btn btn-login">Submit</button>
</form>
</div>

</div>
</div>
)
}
}

export default Login

最佳答案

这是使用 node-fetch 吗?所以我认为您需要将 JSON.stringify() 添加到正文中。

try {

let result = fetch('http://localhost:4000/users/login', {
method: 'POST',
mode:'no-cors',
headers: {
'Content-Type':'application/json',
'Accept':'application/json'
},
body: JSON.stringify({ name: this.state.name, password: this.state.password })
});

result.then((success) => { console.log(success) });
} catch (error) {
console.log(error);
}

链接是指Node Fetch - post with json .我希望它有效。

更新如果您的后端使用的是 ExpressJs,请确保您已添加。

const app = express();

// push them above the router middleware!

// parse application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));

// parse application/json
app.use(express.json());

关于javascript - 通过 Fetch Api 发布请求时 Req.body 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61334553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com