Angular2 http.post无效

时间:2017-07-14 10:37:28

标签: node.js angular

服务:

postJson() {
    var json = JSON.stringify({
      "key": "CT",
      "values": ["FSP", "HMC", "PHYP","hell"]
    });
    let headers = new Headers({'Content-Type':'application/json'});
    //let options = new RequestOptions({headers: headers});
    //headers.append('Access-Control-Allow-Origin', '*');
    return this._http.post('http://localhost:8080/add',json,headers)
      .map(res => res.json());
}

组件:

postData;
onTestPost() {
     this._httpService.postJson()
          .subscribe(
                data=> this.postData = JSON.stringify(data),
                error=> alert(error),
                () => console.log("finished")
          )
   }

Node.js脚本

var express = require('express');
var path = require('path');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.use("/node_modules", express.static('node_modules'));
console.log( __dirname);


app.post('/add', (req, res) => {
  console.log('Received request'+JSON.stringify(req.body));
  fs.writeFile(__dirname + '/CTRoot/data.json', JSON.stringify(req.body), (err) => {

    //if (err) throw err;
    console.log('File written to JSON.json');

    res.setHeader('Access-Control-Allow-Origin', '*')

//Add as many Headers as you want to line below
//If you use "Authentication" Header, insert it like 'Content-type, Authentication'
res.setHeader('Access-Control-Allow-Headers', 'Content-type')
res.setHeader("Content-type", "application/json");
res.setHeader('Access-Control-Allow-Methods', 
'GET,PUT,POST,DELETE,OPTIONS')
    res.send('File written to JSON.json')
  })
});

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

我尝试过添加多个标题,但它无效。

以下输出即将到来 文件写入JSON.json

req.body即将出现空白,但在网络网络请求标题和正文中是预期的

1 个答案:

答案 0 :(得分:1)

为什么使用JSON.stringify创建请求正文?这使得请求正文类型text而不是application/json

所以试试:

postJson() {
    let json = {
      "key": "CT",
      "values": ["FSP", "HMC", "PHYP","hell"]
    };

    let headers = new Headers({'Content-Type':'application/json'});
    return this._http.post('http://localhost:8080/add',json,headers)
      .map(res => res.json());
}

我跑了一个快速测试试图将请求正文发送到text,我的api期望application/json,我收到此错误:

{"code":500,"message":"Content type 'text/plain;charset=UTF-8' not supported"}