[英]can not send json file in post request to nodejs server in ionic2
I am using ionic2 to send requests to a local nodejs server, but the problem is that the request does not hit the server unless I set the header Content-Type
to application/x-www-form-urlencoded
, now the problem is that the body that arrives then is not a json file. 我正在使用ionic2将请求发送到本地nodejs服务器,但是问题是,除非我将标头Content-Type
为application/x-www-form-urlencoded
,否则请求不会到达服务器,现在的问题是然后到达的主体不是json文件。 this is my ionic2 code 这是我的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);
});
}
}
send is called inside a button with (click)='send()'
在(click)='send()'
按钮内调用(click)='send()'
and this is my server code: 这是我的服务器代码:
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...');
when I print the body of this request to the console it prints like this 当我将此请求的主体打印到控制台时,它的打印内容如下
{ '{\n "a": "b"\n}': '' }
now if I change the Content-Type
to application/json
the server does not log anything and ionic page show error with status 0 现在,如果我将Content-Type
更改为application/json
则服务器不会记录任何内容,并且ionic页面显示状态为0的错误
so what is the proper way to send http POST or GET request from ionic2 to a node server ? 那么从ionic2向节点服务器发送http POST或GET请求的正确方法是什么?
I believe you are facing a CORS issues. 我相信您正面临CORS问题。 Enable CORS on your server, by doing the following on the server: 通过在服务器上执行以下操作,在服务器上启用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.