2016-12-31 186 views
4

我有一個nodejs-express服務器(1)與mongodb和web服務器通過nodejs-express與Angularjs進行通信。我試圖做一個POST請求1-> 2,但我得到405 Method Not Allowed(使用郵遞員試過),如果我檢查標題標籤它顯示:Allow →GET, HEAD, OPTIONS從Nodejs發送到Nodejs的請求

app.js - 從1 POST方法:

function sendToDashboard(jsonData) { 
     console.log ("I am here in node: ", jsonData); 

     request({ 
      uri: "http://******.com:9000/getQueryJson", 
      method: "POST", 
      timeout: 10000, 
      followRedirect: true, 
      maxRedirects: 10 
     }, function(error, response, body) { 
      console.log(body); 
     }); 
} 

服務器/ app.js - 2獲得方法:

var bodyParser = require("body-parser"); // Require Body parser module 
var logger = require('morgan'); 
var cookieParser = require('cookie-parser'); 
var express = require('express'); 
var path = require('path'); 
var app = require('express')(); // Require Express module 
var http = require('http').Server(app); // Http server 
var bodyParser = require("body-parser"); // Require Body parser module 

    app.use(logger('dev')); 
    app.use(bodyParser.json()); 
    app.use(bodyParser.urlencoded({ extended: false })); 
    app.use(cookieParser()); 
    app.use(express.static(path.join(__dirname, 'public'))); 

    app.all('*', function(req, res,next) { 


     /** 
     * Response settings 
     * @type {Object} 
     */ 
     var responseSettings = { 
      "AccessControlAllowOrigin": req.headers.origin, 
      "AccessControlAllowHeaders": "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name", 
      "AccessControlAllowMethods": "POST, GET, PUT, DELETE, OPTIONS", 
      "AccessControlAllowCredentials": true 
     }; 

     /** 
     * Headers 
     */ 
     res.header("Access-Control-Allow-Credentials", responseSettings.AccessControlAllowCredentials); 
     res.header("Access-Control-Allow-Origin", responseSettings.AccessControlAllowOrigin); 
     res.header("Access-Control-Allow-Headers", (req.headers['access-control-request-headers']) ? req.headers['access-control-request-headers'] : "x-requested-with"); 
     res.header("Access-Control-Allow-Methods", (req.headers['access-control-request-method']) ? req.headers['access-control-request-method'] : responseSettings.AccessControlAllowMethods); 

     if ('OPTIONS' == req.method) { 
      res.send(200); 
     } 
     else { 
      next(); 
     } 


}); 

app.post('/getQueryJson', function(request, response) { 
     console.log ("I got here"); 
     if(response.statusCode == 200) { 

      console.log("TESTING......") 
      console.log("This is your request: ", request.body); 

      console.log("This is your request: ", JSON.stringify(request.body)) 
      response.send("Query Received"); 
     }else{ 
      response.send(" Error code: " + response.statusCode); 
     } 
    }); 


http.listen(9000,function(){ 
    console.log("Connected & Listen to port 9000"); 
}); 

的文件結構:

(服務器1)

enter image description here

(服務器2)

enter image description here

任何想法,爲什麼它沒有找到我的方法?任何幫助將不勝感激!

+0

敢肯定你的'app.post'需要拿出你的'app.all'過,但我不是100%肯定..... – Claies

+0

我想你無法從響應中「讀取」狀態碼。你只能'設置'狀態碼,如response.status(200)。這是我們'設定'的東西。嘗試避免if-else並執行response.status(200).end(JSON.stringify(request.body)) –

回答

0

如果有人有類似的問題,我解決了我的問題。這個錯誤是我用gulp運行/編譯web服務器的方式。 在我的情況下,下面的工作:

gulp.task('connect', ['styles'], function() { 
     var serveStatic = require('serve-static'); 
     var express  = require('express'); 
     var app   = express(); 
     var bodyParser  = require('body-parser'); 
     var methodOverride = require('method-override'); 


     var port = process.env.PORT || 9000; 

     // added this part ================================================== 
     app.use(bodyParser.json()); // parse application/json 
     app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json 
     app.use(bodyParser.urlencoded({ extended: true })); // parse application/x-www-form-urlencoded 
     app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request. simulate DELETE/PUT 
     // ================================================== 

     app.use(serveStatic('.tmp')); 
     app.use(serveStatic('app')); 
     app.use(express.static(__dirname + 'public')); // set the static files location /public/img will be /img for users 
     app.use('/bower_components', serveStatic('bower_components')); 

     // and this one ================================================== 
     require('./server/app')(app); // pass our application into our routes 
     // =============================================== 


     app.listen(port); 
     console.log('Magic happens on port ' + port);   // shoutout to the user 
     exports = module.exports = app;       // expose app 

    });