Sha*_*mar 4 javascript mongodb node.js express reactjs
当我尝试通过在 body 中传递参数来通过 fetch 方法调用 POST Api 时,我在后端端(Node js 端)得到了 req.body 未定义。此外,当我通过 Postman 通过在 body 中传递参数来调用相同的 POST api 时它工作成功(我得到了 req.body)。后端在 Node js 中,前端在 React js 中。任何帮助将不胜感激。
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
Run Code Online (Sandbox Code Playgroud)
有这个用吗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);
}
Run Code Online (Sandbox Code Playgroud)
链接引用Node Fetch - post with json。我希望它能起作用。
更新 如果您的后端使用的是 ExpressJs,请确保您添加了。
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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8848 次 |
| 最近记录: |