pittuzzo pittuzzo - 4 years ago 178
Node.js Question

Ionic2 : POST request not working

I prepared my server with Node.js (tested with Chrome Postman and everything works fine). It is installed in an Ubuntu 16.04 Server virtual machine and Im testing everything from the host machine (win7). Then I added Ionic2 framework on my virtual machine and start the development of the front-end but I have problem in sending the request POST.

I created a provaider with the following code:

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class MyProvider1 {

data: any;

constructor(public http: Http) {
this.data = null;
}

login(id,pwd){
let headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.post('http://localhost:8080/',
JSON.stringify({
username: id ,
password: pwd
}), {headers: headers})
.subscribe(res => {
console.log(res.json());
});
}
}


It should be working but when the login function is called, my node.js server logs a strange request:


OPTION / 200 0.348 ms -13


Instead of a
POST
request. Moreover, in my host chrome browser the console shows the following failure:


XMLHttpRequest cannot load http://localhost:8080/. Response to
preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:8100' is therefore not allowed
access.


Just for trial I removed the
{headers: headers}
and the
http.post
became:

this.http.post('http://localhost:8080/',
JSON.stringify({
username: id ,
password: pwd
}))
.subscribe(res => {
console.log(res.json());
});


In this way Morgan logs in my Node.js a
POST
request BUT the req.body is empty (if I do
console.log(req.body)
the output will be
{}
).

Just in case, I post in the following part of my server Node.js code:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');

//------------------------------------
//Configuration
//------------------------------------
var config = require('./config.js');
var port = process.env.PORT || config.SERVICE_PORT;
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

//------------------------------------
//Routes
//------------------------------------
app.use('/admin', require('./app/routes/admin.js'));
app.use('/', require('./app/routes/guest.js'));
app.use('/chat', require('./app/routes/chat.js'));

//------------------------------------
//Server Start
//------------------------------------
mongoose.connect(config.database);
app.listen(port);
console.log('server start at port ' + port);


And my /app/routes/guest.js contains the following code:

...
router.route('/')
.get(function(req,res){
res.end('Welcome');
})
.post(function(req,res){
UsersManager.login(req.body.username,req.body.password,function(err,user){
if(err) throw err;
if(!user){
res.json({
success: false,
message: Const.notificationTokenAccessNOK
});
}else{
var token = TokenManager.createToken(user);
res.json({
success: true,
message: Const.notificationTokenAccessOK,
token: token
});
}
});
});

module.exports = router;

Answer Source

You can not perform network request(atleast not directly) from your ionic2 code while testing it in chrome browser.

But if you want to, You can put proxy in ionic.config.json file as followed:

    {
        "proxies": [{
                "path": "/localhost/",
                "proxyUrl": "http://localhost:8080/"
            }] 
}

then you can perform post request as followed :

this.http.post('/localhost/',
                        JSON.stringify({
                            username: id ,
                            password: pwd
                        }))
                    .subscribe(res => {
                        console.log(res.json());
                    }); 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download