Zelda256 2018-05-05 09:50 采纳率: 100%
浏览 804
已采纳

js用post上传数据到服务器,responseText返回错误

我的index.js代码是这样的:
目的是将一个随机数字符串上传到服务器上,然后console.log服务器的返回值。

 var randomNum =  Math.floor(Math.random() * 5).toString();
        console.log(randomNum);
        var xhr = new XMLHttpRequest();  //创建XHR对象
        xhr.open("post","helloWorld.js");
        xhr.onreadystatechange = function() {
            if(xhr.readyState == 4) {
                if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
                    console.log("ok:"+xhr.status);
                    console.log(xhr.responseText);
                }else {
                    alert("Request was unsuccessful:" + xhr.status);
                }
            } //if
        };
        xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
        xhr.send(randomNum); 

然后我的运行在服务器上的node.js代码名为helloWorld.js是这样的:
目的是接收浏览器传来的随机数,然后返回“ok”

 //引入模块
var http = require("http");
var url = require("url");
var querystring = require("querystring");
console.log("!!!");
//创建服务器
var server = http.createServer( function(request, response) {
        console.log("?????");
        console.log(request);
        var getData = "";
        request.on("data", function(chunk){ getData += chunk;});
        console.log(getData);
        //response.writeHeader(200,{"Content-Type":"text/javascript;charset=UTF-8"});
        response.write("ok");
        response.end();
});

//设置监听窗口
server.listen(3333,function(){
        console.log("Server running...");
});

当我打开网站的时候:
1.chorme的控制台输出如下:
第一行是我产生的随机数
第二行是console.log("ok:"+xhr.status);的输出
第三行是console.log(xhr.responseText);的输出,问题出在这里,没有返回“ok”,而是显示了服务器上的文件helloWorld.js的代码,这是为什么呢?如何显示正确的结果“ok”?

图片说明

2.云服务器的控制台输出的结果如下:
这里甚至没有输出“????”,这个我也不知道是为什么。
图片说明

请求指教!十分感谢!

  • 写回答

4条回答 默认 最新

  • anchenyou88 2018-05-05 10:33
    关注

    是不是被什么防火墙给拦截了所以没有成功

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog