【发布时间】:2017-11-21 19:22:12
【问题描述】:
我正在使用 ionic2 向本地 nodejs 服务器发送请求,但问题是请求不会到达服务器,除非我将标头 Content-Type 设置为 application/x-www-form-urlencoded ,现在问题是到达的正文then 不是 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()'的按钮内调用发送
这是我的服务器代码:
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 请求的正确方法是什么?
【问题讨论】:
标签: json node.js angular http ionic2