在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ js用post上傳數(shù)據(jù)到服務(wù)器,responseText返回錯誤

js用post上傳數(shù)據(jù)到服務(wù)器,responseText返回錯誤

我的index.js代碼是這樣的:
目的是將一個隨機數(shù)字符串上傳到服務(wù)器上,然后console.log服務(wù)器的返回值。

var randomNum =  Math.floor(Math.random() * 5).toString();
        console.log(randomNum);
        var xhr = new XMLHttpRequest();  //創(chuàng)建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); 

然后我的運行在服務(wù)器上的node.js代碼名為helloWorld.js是這樣的:
目的是接收瀏覽器傳來的隨機數(shù),然后返回“ok”

//引入模塊
var http = require("http");
var url = require("url");
var querystring = require("querystring");
console.log("!!!");
//創(chuàng)建服務(wù)器
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();
});

//設(shè)置監(jiān)聽窗口
server.listen(3333,function(){
        console.log("Server running...");
});

當(dāng)我打開網(wǎng)站的時候:
1.chorme的控制臺輸出如下:
第一行是我產(chǎn)生的隨機數(shù)
第二行是console.log("ok:"+xhr.status);的輸出
第三行是console.log(xhr.responseText);的輸出,問題出在這里,沒有返回“ok”,而是顯示了服務(wù)器上的文件helloWorld.js的代碼,這是為什么呢?如何顯示正確的結(jié)果“ok”?

clipboard.png

2.云服務(wù)器的控制臺輸出的結(jié)果如下:
這里甚至沒有輸出“????”,這個我也不知道是為什么。

clipboard.png

請求指教!十分感謝!

回答
編輯回答
尐潴豬

你肯定環(huán)境沒整好,用了一個另外的虛擬服務(wù)運行的隨機數(shù) js 的 html,如 live-serverhttp-server 之類的?
node 部分也沒見你寫頁面服務(wù),肯定不是拿你寫的 node 運行的 html。同時對 helloWorld.js 的請求都沒見你寫端口號,肯定直接走了這個虛擬服務(wù)的接口(然后虛擬服務(wù)就直接走了它提供的靜態(tài)文件的服務(wù)),不是走的你寫的node的。


評論里的錯誤是跨域引起的,改為

response.writeHeader(200, {
 "Content-Type":"text/javascript;charset=UTF-8",
 // 允許跨域源
 "Access-Control-Allow-Origin": "*"
 // 看情況添加其他允許跨域請求頭,百度查
});
2017年7月16日 18:21
編輯回答
孤毒
xhr.open("post","http://127.0.0.1:3333");

跨域處理:
helloWorld.js

var server = http.createServer( function(request, response) {
    response.setHeader('Access-Control-Allow-Origin', '*');
    response.setHeader('Access-Control-Allow-Methods', '*');
    ...
2017年5月30日 01:39