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)
(服務器2)
任何想法,爲什麼它沒有找到我的方法?任何幫助將不勝感激!
敢肯定你的'app.post'需要拿出你的'app.all'過,但我不是100%肯定..... – Claies
我想你無法從響應中「讀取」狀態碼。你只能'設置'狀態碼,如response.status(200)。這是我們'設定'的東西。嘗試避免if-else並執行response.status(200).end(JSON.stringify(request.body)) –