从Nodejs发送请求到Nodejs

时间:2016-12-31 09:38:07

标签: angularjs node.js express

我有一个nodejs-express服务器(1),它通过Angularjs与nodejs-express中的mongodb和web服务器(2)进行通信。我正在尝试发布帖子请求1-> 2但我收到405 Method Not Allowed(尝试使用邮递员),如果我查看标题标签,则会显示:Allow →GET, HEAD, OPTIONS

app.js - 从1开始发布方法:

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

server / 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

知道为什么它找不到我的方法吗?任何帮助将不胜感激!

1 个答案:

答案 0 :(得分: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

    });