簡體   English   中英

Ionic2:POST請求不起作用

[英]Ionic2 : POST request not working

我使用Node.js准備了服務器(已通過Chrome Postman測試,一切正常)。 它安裝在Ubuntu 16.04 Server虛擬機中,並且可以對主機(win7)上的所有內容進行即時測試。 然后,我在虛擬機上添加了Ionic2框架,並開始了前端的開發,但是在發送請求POST時遇到問題。

我使用以下代碼創建了一個證明程序:

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

它應該可以正常工作,但是當調用登錄功能時,我的node.js服務器記錄了一個奇怪的請求:

選項/ 200 0.348毫秒-13

而不是POST請求。 此外,在我的主機Chrome瀏覽器中,控制台顯示以下故障:

XMLHttpRequest無法加載http:// localhost:8080 / 對預檢請求的響應未通過訪問控制檢查:在所請求的資源上不存在“ Access-Control-Allow-Origin”標頭。 因此,不允許訪問源' http:// localhost:8100 '。

只是為了試用,我刪除了{headers: headers} ,而http.post變成了:

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

這樣,Morgan將我的Node.js登錄到POST請求中,但req.body為空(如果我執行console.log(req.body)則輸出為{} )。

以防萬一,我在服務器的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);

我的/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;

在chrome瀏覽器中測試時,您無法從ionic2代碼執行網絡請求(至少不是直接執行)。

但是,如果願意,您可以按如下所示將代理放入ionic.config.json文件:

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

那么您可以按照以下步驟執行發布請求:

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