这与Stream data with Node.js差不多,但我觉得这个问题没有得到充分的回答.

我试图使用jQuery ajax调用(get、load、getJSON)在页面和 node 之间传输数据.js服务器.我可以从浏览器中点击地址,看到"你好,世界!"!",但当我从我的页面try 此操作时,它失败了,并显示我没有得到响应.我设置了一个简单的测试页面和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>

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

推荐答案

如果您的简单测试页面位于hello world node 之外的其他协议/域/端口上.例如,您正在执行跨域请求,并且违反了same origin policy条规则,因此您的jQuery ajax调用(get和load)正在悄silent息地失败.为了让这个跨域工作,你应该使用基于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);

和客户端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);
        }
    });
});

还有其他方法可以实现这一点,例如设置reverse proxy或完全使用express这样的框架构建web应用程序.

Node.js相关问答推荐

如何使用jq将依赖项添加到package.json中

即使DDB键不存在, node Lambda也不会失败,并返回NULL作为结果

无法使用Sequelize连接AWS RDS

如何从shell脚本中计算ecmascript模块?

无法从MongoDB文档中保存的对象数组中获取对象的属性

为什么 Cors 在 NodeJS 中不起作用

如何模拟 mysql2 `getConnection`

将 null 推入管道后,node.js 可写完成未发出

为什么当我使用waitForSelector时 Puppeteer 导致我的测试套件挂起 30 秒,即使我在页面和浏览器上调用关闭?

Winston http 日志(log)级别的行为与 info 不同

即使部署成功,也不会触发 Firebase 函数来填充 Firestore 集合.为什么?

Node.js 大文件上传到 MongoDB 阻塞了事件循环和工作池

如何正确使用 package.json 中的关键字属性?

如何使用 UglifyJS 缩小文件夹中的多个 Javascript 文件?

Node.js + Express 上的多个视图路径

在多个 .env 文件之间切换,例如 .env.development 和 node.js

如何在不全局安装的情况下在 Node REPL 中要求 node 模块?

我可以有条件地将 where() 子句添加到我的 knex 查询吗?

nodejs:Ajax 与 Socket.IO,优缺点

如何阻止 babel 将this转换为undefined(并插入use strict)