2017-07-14 70 views
1

服務:Angular2 http.post不工作​​

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來了空,但在網絡的網絡請求頭和身體,作爲你爲什麼要使用JSON.stringify創建請求預期

+1

而不是' .map(res => res.json());'你可以嘗試'.map(res => res.text());'或者只是'.map(res => res);'? – echonax

+0

JSON.parse:JSON數據的第1行第1列出現的意外字符,表示返回的數據中有某些內容不應該在那裏。可能是錯誤消息。查看檢索到的數據並將其發佈到此處。不要看着身體,看看網絡標籤的反應。 – Doomenik

+2

請閱讀[在什麼情況下,我可以添加「緊急」或其他類似的短語到我的問題,以獲得更快的答案?](/ meta.stackoverflow.com/q/326569) - 總結是,這不是這是解決志願者問題的理想方式,可能會對獲得答案產生反作用。請不要將這添加到您的問題。 – halfer

回答

1

身體?這使請求主體類型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"}