Javascript 如何在 node.js 中使用 jQuery ajax 调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5373987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:55:03  来源:igfitidea点击:

how to use jQuery ajax calls with node.js

javascriptjqueryhtmlajaxnode.js

提问by briznad

This is similar to Stream data with Node.js, but I don't feel that question was answered sufficiently.

这类似于Node.js 的 Stream data,但我觉得这个问题没有得到足够的回答。

I'm trying to use a jQuery ajax call (get, load, getJSON) to transfer data between a page and a node.js server. I can hit the address from my browser and see 'Hello World!", but when I try this from my page, it fails and shows that I get no response back. I setup a simple test page and hello world example to test this:

我正在尝试使用 jQuery ajax 调用(get、load、getJSON)在页面和 node.js 服务器之间传输数据。我可以从我的浏览器点击地址并看到“Hello World!”,但是当我从我的页面尝试这个时,它失败并显示我没有得到任何回复。我设置了一个简单的测试页面和 hello world 示例来测试这个:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>get test</title> 
</head>
<body>
    <h1>Get Test</h1>
    <div id="test"></div>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js"></script>
    <script>
        $(document).ready(function() {
            //alert($('h1').length);
            $('#test').load('http://192.168.1.103:8124/');
            //$.get('http://192.168.1.103:8124/', function(data) {                
            //  alert(data);
            //});
        });
    </script>
</body>
</html>

and

var http = require('http');

http.createServer(function (req, res) {
    console.log('request received');
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(8124);

回答by yojimbo87

If your simple test page is located on other protocol/domain/port than your hello world node.js example you are doing cross-domain requests and violating same origin policytherefore your jQuery ajax calls (get and load) are failing silently. To get this working cross-domain you should use JSONPbased format. For example node.js code:

如果您的简单测试页面位于 hello world node.js 示例之外的其他协议/域/端口上,则您正在执行跨域请求并违反同源策略,因此您的 jQuery ajax 调用(get 和 load)将无声无息地失败。要获得此跨域工作,您应该使用基于JSONP的格式。例如 node.js 代码:

var http = require('http');

http.createServer(function (req, res) {
    console.log('request received');
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('_testcb(\'{"message": "Hello world!"}\')');
}).listen(8124);

and client side JavaScript/jQuery:

和客户端 JavaScript/jQuery:

$(document).ready(function() {
    $.ajax({
        url: 'http://192.168.1.103:8124/',
        dataType: "jsonp",
        jsonpCallback: "_testcb",
        cache: false,
        timeout: 5000,
        success: function(data) {
            $("#test").append(data);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert('error ' + textStatus + " " + errorThrown);
        }
    });
});

There are also other ways how to get this working, for example by setting up reverse proxyor build your web application entirely with framework like express.

还有其他方法可以让这个工作,例如通过设置反向代理或完全使用express 等框架构建您的 Web 应用程序。

回答by Michael Dausmann

Thanks to yojimbo for his answer. To add to his sample, I wanted to use the jquery method $.getJSON which puts a random callback in the query string so I also wanted to parse that out in the Node.js. I also wanted to pass an object back and use the stringify function.

感谢 yojimbo 的回答。为了添加到他的示例中,我想使用 jquery 方法 $.getJSON,它在查询字符串中放置一个随机回调,所以我还想在 Node.js 中解析它。我还想传回一个对象并使用 stringify 函数。

This is my Client Side code.

这是我的客户端代码。

$.getJSON("http://localhost:8124/dummy?action=dostuff&callback=?",
function(data){
  alert(data);
},
function(jqXHR, textStatus, errorThrown) {
    alert('error ' + textStatus + " " + errorThrown);
});

This is my Server side Node.js

这是我的服务器端 Node.js

var http = require('http');
var querystring = require('querystring');
var url = require('url');

http.createServer(function (req, res) {
    //grab the callback from the query string   
    var pquery = querystring.parse(url.parse(req.url).query);   
    var callback = (pquery.callback ? pquery.callback : '');

    //we probably want to send an object back in response to the request
    var returnObject = {message: "Hello World!"};
    var returnObjectString = JSON.stringify(returnObject);

    //push back the response including the callback shenanigans
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(callback + '(\'' + returnObjectString + '\')');
}).listen(8124);

回答by Adrien

I suppose your html page is hosted on a different port. Same origin policy requiresin most browsers that the loaded file be on the same port than the loading file.

我想您的 html 页面托管在不同的端口上。在大多数浏览器中,同源策略要求加载的文件与加载文件位于同一端口。

回答by Adrien

Use something like the following on the server side:

在服务器端使用类似以下内容:

http.createServer(function (request, response) {
    if (request.headers['x-requested-with'] == 'XMLHttpRequest') {
        // handle async request
        var u = url.parse(request.url, true); //not needed

        response.writeHead(200, {'content-type':'text/json'})
        response.end(JSON.stringify(some_array.slice(1, 10))) //send elements 1 to 10
    } else {
        // handle sync request (by server index.html)
        if (request.url == '/') {
            response.writeHead(200, {'content-type': 'text/html'})
            util.pump(fs.createReadStream('index.html'), response)
        } 
        else 
        {
            // 404 error
        }
    }
}).listen(31337)