通过提取Api发送请求时,请求实体未定义

时间:2020-04-21 01:25:24

标签: javascript node.js reactjs mongodb express

当我尝试通过在体内传递参数通过fetch方法调用POST Api时,我在后端侧(节点js端)获得了req.body未定义。此外,当我通过传递参数通过Postman调用Same POST api时在体内然后成功工作(我得到了要求的身体)。后端在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

3 个答案:

答案 0 :(得分:0)

您必须使用JSON.stringify将正文数据转换为JSON。

还要确保在后端启用了cors

问题出在mode: 'no-cors'上,请删除它。因为在application/json模式下不允许no-cors

请注意,模式:“ no-cors”仅在请求中允许使用一组有限的标头:

  1. 接受
  2. 接受语言
  3. Content-Language Content-Type,值为 application / x-www-form-urlencoded,multipart / form-data或 文字/纯文字

尝试一下。

submitHandler = (e) => {
    e.preventDefault();
    console.log(this.state);
    try {
        let result = fetch('http://localhost:4000/users/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify({ name: this.state.name, password: this.state.password })
        })
        result.then((sucess) => { console.log(sucess) })
    } catch (error) {
        console.log(error)
    }

}

答案 1 :(得分:0)

此外,您将需要在构造函数中绑定函数SubmitHandler,以访问“ this

 this.submitHandler =this.submitHandler .bind(this);

答案 2 :(得分:0)

这是否使用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。我希望它能起作用。

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

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());