因此,我正在嘗試制作一個(gè)非?;镜膎ode.js服務(wù)器,該服務(wù)器接受字符串請求,從數(shù)組中隨機(jī)選擇一個(gè),然后返回所選的字符串。不幸的是,我遇到了一些問題。這是前端: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;}這應(yīng)該將請求發(fā)送到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);很明顯,這里有幾處錯(cuò)誤:我感覺到我“連接”這兩個(gè)文件的xmlhttp.open方式在方法和使用中都無法正確response.on發(fā)送字符串回到前端。我對如何在localhost上調(diào)用此頁面感到有些困惑。前端名為index.html,服務(wù)器的地址為8001。初始化server.js后,我應(yīng)該在localhost上訪問哪個(gè)地址才能訪問初始的html頁面?我應(yīng)該將其更改為.listen(index.html)或類似的名稱嗎?我如何實(shí)現(xiàn)這一點(diǎn)(使用.responsetext等)還有其他明顯的問題嗎?(對冗長的多問題帖子很抱歉,但是各種教程和node.js源均假設(shè)用戶已經(jīng)對這些事情有所了解。)
基本的Ajax使用node.js發(fā)送/接收
人到中年有點(diǎn)甜
2019-12-12 14:52:22