【问题标题】:can not send json file in post request to nodejs server in ionic2无法将 post 请求中的 json 文件发送到 ionic2 中的 nodejs 服务器
【发布时间】: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


    【解决方案1】:

    我相信您正面临 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));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-18
      • 1970-01-01
      • 2016-07-03
      • 1970-01-01
      • 2016-03-31
      • 2013-07-29
      • 1970-01-01
      相关资源
      最近更新 更多