简体   繁体   English

Ionic2:POST请求不起作用

[英]Ionic2 : POST request not working

I prepared my server with Node.js (tested with Chrome Postman and everything works fine). 我使用Node.js准备了服务器(已通过Chrome Postman测试,一切正常)。 It is installed in an Ubuntu 16.04 Server virtual machine and Im testing everything from the host machine (win7). 它安装在Ubuntu 16.04 Server虚拟机中,并且可以对主机(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. 然后,我在虚拟机上添加了Ionic2框架,并开始了前端的开发,但是在发送请求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: 它应该可以正常工作,但是当调用登录功能时,我的node.js服务器记录了一个奇怪的请求:

OPTION / 200 0.348 ms -13 选项/ 200 0.348毫秒-13

Instead of a POST request. 而不是POST请求。 Moreover, in my host chrome browser the console shows the following failure: 此外,在我的主机Chrome浏览器中,控制台显示以下故障:

XMLHttpRequest cannot load http://localhost:8080/ . XMLHttpRequest无法加载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. 对预检请求的响应未通过访问控制检查:在所请求的资源上不存在“ Access-Control-Allow-Origin”标头。 Origin ' http://localhost:8100 ' is therefore not allowed access. 因此,不允许访问源' http:// localhost:8100 '。

Just for trial I removed the {headers: headers} and the http.post became: 只是为了试用,我删除了{headers: headers} ,而http.post变成了:

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 {} ). 这样,Morgan将我的Node.js登录到POST请求中,但req.body为空(如果我执行console.log(req.body)则输出为{} )。

Just in case, I post in the following part of my server Node.js code: 以防万一,我在服务器的Node.js代码的以下部分中发布:

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: 我的/app/routes/guest.js包含以下代码:

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

You can not perform network request(atleast not directly) from your ionic2 code while testing it in chrome browser. 在chrome浏览器中测试时,您无法从ionic2代码执行网络请求(至少不是直接执行)。

But if you want to, You can put proxy in ionic.config.json file as followed: 但是,如果愿意,您可以按如下所示将代理放入ionic.config.json文件:

    {
        "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());
                    }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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