[英]can not send json file in post request to nodejs server in ionic2
我正在使用ionic2將請求發送到本地nodejs服務器,但是問題是,除非我將標頭Content-Type
為application/x-www-form-urlencoded
,否則請求不會到達服務器,現在的問題是然后到達的主體不是json文件。 這是我的ionic2代碼
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController, public http: Http) {}
send(){
let headers = new Headers({
// 'Content-Type': 'application/json'
'Content-Type': 'application/x-www-form-urlencoded'
});
let body = {a: 'b'};
this.http.post('http://localhost:8010/api/test', body, {headers: headers})
.map(res => res.json())
.subscribe(data => {
console.log('response11: ', data);
}, err => {
console.log('ERR: ', err);
});
}
}
在(click)='send()'
按鈕內調用(click)='send()'
這是我的服務器代碼:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.post('/api/test', function(req, res){
console.log(req.body);
res.send('from nodejs');
});
app.listen(8010);
console.log('listening on port 8010...');
當我將此請求的主體打印到控制台時,它的打印內容如下
{ '{\n "a": "b"\n}': '' }
現在,如果我將Content-Type
更改為application/json
則服務器不會記錄任何內容,並且ionic頁面顯示狀態為0的錯誤
那么從ionic2向節點服務器發送http POST或GET請求的正確方法是什么?
我相信您正面臨CORS問題。 通過在服務器上執行以下操作,在服務器上啟用CORS:
const cors = require("cors");
const originsWhitelist = [
"http://localhost:8100"
];
const corsOptions = {
origin: function (origin, callback) {
var isWhitelisted = originsWhitelist.indexOf(origin) !== -1;
callback(null, isWhitelisted);
},
credentials: true
};
//here is the magic
app.use(cors(corsOptions));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.