简体   繁体   中英

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. this is my ionic2 code

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()'

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

so what is the proper way to send http POST or GET request from ionic2 to a node server ?

I believe you are facing a CORS issues. Enable CORS on your server, by doing the following on the server:

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM