如何将FormData从Angular 2发送到nodejs?

我正在使用这个代码:

var creds = "username=" + 'user' + "&password=" + 'password'; var headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded'); http.post('http://localhost:3000/', creds, { headers : headers }) .map(res => res.json()) .subscribe( data => this.logData(data), err => this.logError(err), () => console.log('Quote Complete') ); 

NodeJs在this.request.body上获得了json {username:'user',password:'password'}。 但我需要JSON像{字段:{用户名:'用户',密码:'密码'}}

如果你只想使用url编码的forms,你不能。 实际上,Node应用程序会将string内容( username=user&password=somepwd )转换/反序列化为一个简单(平坦)的JavaScripty对象。

为了在Node应用程序中获得您想要的数据(特定格式),您需要切换到您的请求负载的application/json内容types,如下所述:

 var creds = { fields: { username: 'user', password: 'password' } } var headers = new Headers(); headers.append('Content-Type', 'application/json'); http.post('http://localhost:3000/', JSON.stringify(creds), { headers : headers }) .map(res => res.json()) .subscribe( data => this.logData(data), err => this.logError(err), () => console.log('Quote Complete') ); 

别忘了在Node应用程序中注册正确的解串器。 例如使用Express:

 var express = require('express'); var application = express(); application.use(bodyParser.json()); 

希望它能帮助你,Thierry

创build指定格式的对象,使用json.stringify从中创build一个string并将其发送到node.js服务器。