因此,我正在嘗試制作一個非?;镜膎ode.js服務器,該服務器接受字符串請求,從數組中隨機選擇一個,然后返回所選的字符串。不幸的是,我遇到了一些問題。這是前端:function newGame(){ guessCnt=0; guess=""; server(); displayHash(); displayGuessStr(); displayGuessCnt();}function server(){ xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET","server.js", true); xmlhttp.send(); string=xmlhttp.responseText;}這應該將請求發送到server.js:var http = require('http');var choices=["hello world", "goodbye world"];console.log("server initialized");http.createServer(function(request, response){ console.log("request recieved"); var string = choices[Math.floor(Math.random()*choices.length)]; console.log("string '" + string + "' chosen"); response.on(string); console.log("string sent");}).listen(8001);很明顯,這里有幾處錯誤:我感覺到我“連接”這兩個文件的xmlhttp.open方式在方法和使用中都無法正確response.on發送字符串回到前端。我對如何在localhost上調用此頁面感到有些困惑。前端名為index.html,服務器的地址為8001。初始化server.js后,我應該在localhost上訪問哪個地址才能訪問初始的html頁面?我應該將其更改為.listen(index.html)或類似的名稱嗎?我如何實現這一點(使用.responsetext等)還有其他明顯的問題嗎?(對冗長的多問題帖子很抱歉,但是各種教程和node.js源均假設用戶已經對這些事情有所了解。)
基本的Ajax使用node.js發送/接收
人到中年有點甜
2019-12-12 14:52:22