【问题标题】:Why does the server not receive the ajax request?为什么服务器收不到ajax请求?
【发布时间】:2015-07-07 09:48:51
【问题描述】:

我必须使用集成测试来测试网站。该网站将所有请求发送到代理:

var express = require("express"),
    http = require("http"),
    port = (process.env.PORT || 8001),
    server = module.exports = express(),
    httpProxy = require('http-proxy');

var proxy = httpProxy.createProxyServer();

// SERVER CONFIGURATION
// ====================
server.configure(function() {
    server.use(function(req, res, next) {
        console.log(req.url);
        if (req.url.indexOf('/any/thing') === 0) {
            console.log("url: " + req.url + ",\nheaders: " + req.headers + ",\nmethod: " + req.method);
            proxy.web(req, res, {target: 'http://127.0.0.1:1337'});
        } else {
            //console.log("url: " + req.url + ",\nheaders: " + req.headers + ",\nmethod: " + req.method);
            next();
        }
    });
    server.use('/anything', express["static"](__dirname + "/../public"));

    server.use(express.errorHandler({

        dumpExceptions: true,

        showStack: true

    }));

    server.use(express.bodyParser());

    server.use(server.router);

});

// SERVER
// ======

// Start Node.js Server
http.createServer(server).listen(port);

这个代理应该和这个服务器通信:

var http = require('http');
http.createServer(function (req, res) {
    console.log("url: " + req.url + ",\nheaders: " + req.headers + ",\nmethod: " + req.method);
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end("{'user': 'garrarufa', 'loginToken': 'token'}");
}).listen(1337, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1337/');

使用ajax登录:

$.ajax(this.apipath + "/login/", {
    type: "GET",
    async: false,
    success: function(...){...},
    error: function(...){...}
});

当我运行登录请求时,立即调用error。该请求不会出现在代理服务器上。至少代理不会向控制台打印任何内容。这里发生了什么? ajax请求不应该发给服务器吗?

【问题讨论】:

    标签: javascript ajax node.js proxy server


    【解决方案1】:

    您的代理正在运行

    port = (process.env.PORT || 8001),
    

    您的客户端代码发送到哪个端口? IE。 this.apipath 设置为什么?

    $.ajax(this.apipath + "/login/", {
        type: "GET",
        async: false,
        success: function(...){...},
        error: function(...){...}
    });
    

    【讨论】:

    • apipath = 'api'。我不确定这意味着什么,因为在原始代码(有效)中它说:if (hostname === "localhost" || ...) this.apipath = "api"; 代理也收到许多请求。但不是这个
    • 使用 Fiddler 查看您尝试的 http 请求对代理的更详细响应。
    猜你喜欢
    • 1970-01-01
    • 2022-07-13
    • 2020-10-19
    • 1970-01-01
    • 2021-08-23
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多