Angular 5使用Nodejs发布数据 - 正文格式错误

时间:2018-06-18 13:38:17

标签: javascript node.js angular angular5

我使用nodejs作为angular 5应用程序的后端。当我使用http post请求发布数据时,它会在nodejs中以错误的形式出现(值为属性) - 这是我的角度5的服务代码 -

login(email: string, password: string) {
    let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
    let options = new RequestOptions({ headers: headers });
    let body = { EmailAddress: email, Password: password };

    return this.http.post('http://localhost:3000/api/user/login', body, options )
        .map((response: Response) => {
            let user = response.json();
            if (user && user.token) {
                localStorage.setItem('currentUser', JSON.stringify(user));
            }
        });
}

这是Node API - 在正文中我获得了作为属性的价值

app.post('/api/user/login', urlencodedBodyparser, function (req, res) {
    console.log(req.body);
    User.find({ "EmailAddress": req.body["EmailAddress"], "Password": req.body["Password"] }, function (err, users) {
        console.log(users.length);
        if (err != null) {
            sendError(err, res);
        }
        if (users != null) {
            var count = users.length;
            if (count > 0) {
                response.data = users[0];
                res.json(response);
            }
            else {
                sendError({ message :'No user found'}, res);
                console.log("Login Failed");
            }
        }
        else {
            sendError(err, res);
        }
    })
});

正文解析器代码 -

var bodyParser = require(' body-parser');

var urlencodedBodyparser = bodyParser.urlencoded({extended:false});

app.use(urlencodedBodyparser);

enter image description here

2 个答案:

答案 0 :(得分:2)

尝试将标题内容类型更改为json

  

应用/ JSON

像这样:

    options() {
        const headers = new Headers({
            'content-type': 'application/json'
        });
        const options = new RequestOptions({ headers: headers });

        return options;
    }




   login(): Observable<any> {
        return this.http.post('http://localhost:3000/api/user/login', this.options()).
            map((res: Response) => res.json());
    }

答案 1 :(得分:1)

您需要使用正文解析器中间件https://github.com/expressjs/body-parser
以下是更多信息What does body-parser do with express?
试着用这个:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));