javascript - 意外的空白 Ajax 响应文本

标签 javascript html ajax node.js

我尝试使用 Node.js 测试我的 Ajax 代码。我以前没有用过它,所以我是新手。 这是我的代码:

<script>
  var xmlHttp = false;
    /*@cc_on @*/
    /*@if (@_jscript_version >= 5)
    try {
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e2) {
        xmlHttp = false;
      }
    }
    @end @*/

  if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
    xmlHttp = new XMLHttpRequest();
  }

  function callServer() {
    var url = "http://localhost:8888/";
    xmlHttp.open("GET", url, true);
    xmlHttp.onreadystatechange = updatePage;
    xmlHttp.send(null);
  }

  function updatePage() {
    if (xmlHttp.readyState == 4) {
      var response = xmlHttp.responseText;
      alert(response);
    }
  }
</script>

还有我的 Node.js 服务器:

var http = require("http");

http.createServer(function(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Test");
  response.end("Test");
}).listen(8888);

我运行带有属性的脚本:onclick="callServer()"。警报什么也没告诉我。谢谢。

最佳答案

你的代码工作正常,问题是你在不同的域或端口上运行你的客户端然后你的服务器运行。

尝试在 http://localhost:8888/ 上运行您的客户端.

编辑:

使用 Express 包非常简单:

var app = require('express')();

app.get('/', function(req, res) {
  res.send('Test');
});

app.get('/index.html', function(req, res) {
  res.sendfile('index.html');
});

app.listen(8888, function() {
  console.log('Server started at port 8888');
});

编辑#2

没有 express :

var http = require('http'),
    fs   = require('fs');    

var server = http.createServer(function(req, res) {
  fs.readFile('./index.html', function(err, data) {
    res.writeHeader(200, { 'Content-Type': 'text/html' });
    res.write(data);
    res.end();
  });
}).listen(8888);

server.on('request', function(req, res) {
  if(req.url == '/test') {
    res.writeHeader(200, { 'Content-Type': 'text/plain' });
    res.write('Test');
    res.end();
  }
});

编辑#3

要提供静态 Assets ,请使用 express.static像这样的中间件:

var express = require('express'),
    app     = express();

app.use(express.static(__dirname + '/public'));

您应该将您的资源放在根目录的 public 目录中。

关于javascript - 意外的空白 Ajax 响应文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31347236/

相关文章:

javascript - 了解 Skrollr 数据值

javascript - 使用 discord.js 发送消息

html - CSS:我应该使用 mixin 还是类?

c# - HTML Agility Pack 不更改文本节点的文本

javascript - 重新加载 jquery 和 js 库

Ajax 请求不对所有人开放

javascript - JS - 获取 #id 而不是 .val()

javascript - 下载文件;使用 .execScript VBA 执行 JavaScript 函数

html - 将我的元素切换为 "position: absolute"可防止它占用全宽

ajax - iFrame - 搜索引擎如何读取它们?