[英]Basic Ajax send/receive with node.js
所以我正在嘗試制作一個非常基本的 node.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
將字符串發送回前端時都不正確。
我對如何在本地主機上調用此頁面感到有些困惑。 前端命名為 index.html,服務器發布到 8001。在我初始化 server.js 后,我應該在 localhost 上訪問哪個地址才能訪問初始 html 頁面? 我應該將其更改為.listen(index.html)
或類似的內容嗎?
我如何實現這個(使用.responsetext
等)還有其他明顯的問題.responsetext
(對不起,多問題的帖子很長,但各種教程和 node.js 源代碼都假設用戶已經了解這些東西。)
您的請求應該發送到服務器,而不是實例化它的 server.js 文件。 所以,請求應該是這樣的: xmlhttp.open("GET","http://localhost:8001/", true);
此外,您正在嘗試為前端 (index.html) 提供服務並在同一 URI 上提供 AJAX 請求。 為此,您必須向 server.js 引入邏輯,以區分 AJAX 請求和普通的 http 訪問請求。 為此,您需要引入 GET/POST 數據(即調用http://localhost:8001/?getstring=true
)或為 AJAX 請求使用不同的路徑(即調用http://localhost:8001/getstring
)。 然后在服務器端,您需要檢查請求對象以確定要在響應上寫入什么內容。 對於后一個選項,您需要使用 'url' 模塊來解析請求。
您正確地調用了listen()
但錯誤地編寫了響應。 首先,如果您希望在導航到http://localhost:8001/時提供 index.html,您需要使用response.write()
或response.end()
將文件的內容寫入response.end()
。 首先,您需要包含fs=require('fs')
以訪問文件系統。 然后,您需要實際提供文件。
如果您異步使用 XMLHttpRequest 需要指定回調函數(第三個參數 = true,正如您所做的那樣)並且想要對響應執行某些操作。 按照您現在的方式, string
將是undefined
(或者可能是null
),因為該行將在 AJAX 請求完成之前執行(即 responseText 仍然為空)。 如果同步使用(第三個參數=false),就可以像以前一樣編寫內聯代碼。 不建議這樣做,因為它會在請求期間鎖定瀏覽器。 異步操作通常與 onreadystatechange 函數一起使用,一旦完成就可以處理響應。 您需要學習 XMLHttpRequest 的基礎知識。 從這里開始。
這是一個包含上述所有內容的簡單實現:
服務器.js:
var http = require('http'),
fs = require('fs'),
url = require('url'),
choices = ["hello world", "goodbye world"];
http.createServer(function(request, response){
var path = url.parse(request.url).pathname;
if(path=="/getstring"){
console.log("request recieved");
var string = choices[Math.floor(Math.random()*choices.length)];
console.log("string '" + string + "' chosen");
response.writeHead(200, {"Content-Type": "text/plain"});
response.end(string);
console.log("string sent");
}else{
fs.readFile('./index.html', function(err, file) {
if(err) {
// write an error response or nothing here
return;
}
response.writeHead(200, { 'Content-Type': 'text/html' });
response.end(file, "utf-8");
});
}
}).listen(8001);
console.log("server initialized");
前端(index.html 的一部分):
function newGame()
{
guessCnt=0;
guess="";
server();
displayHash();
displayGuessStr();
displayGuessCnt();
}
function server()
{
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://localhost:8001/getstring", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
string=xmlhttp.responseText;
}
}
xmlhttp.send();
}
您需要熟悉 AJAX。 使用 mozilla 學習中心了解 XMLHttpRequest。 在您可以使用基本的 XHR 對象之后,您很可能希望使用一個好的 AJAX 庫,而不是手動編寫跨瀏覽器的 AJAX 請求(例如,在 IE 中,您需要使用 ActiveXObject 而不是 XHR)。 jQuery 中的 AJAX 非常出色,但如果您不需要jQuery提供的所有其他功能,請在此處找到一個好的 AJAX 庫: http : //microjs.com/ 。 您還需要熟悉 node.js 文檔,可在此處找到。 在http://google.com 上搜索一些好的 node.js 服務器和靜態文件服務器教程。 http://nodetuts.com是一個很好的起點。
更新:我已將上面代碼中的response.sendHeader()
更改為新的response.writeHead()
!!!
Express 讓這種東西變得非常直觀。 語法如下所示:
var app = require('express').createServer();
app.get("/string", function(req, res) {
var strings = ["rad", "bla", "ska"]
var n = Math.floor(Math.random() * strings.length)
res.send(strings[n])
})
app.listen(8001)
如果您在客戶端使用 jQuery,您可以執行以下操作:
$.get("/string", function(string) {
alert(string)
})
我遇到了由&符號提供的代碼(nodejs 0.10.13)的以下錯誤:
access-control-allow-origin 不允許來源
問題已解決更改
response.writeHead(200, {"Content-Type": "text/plain"});
到
response.writeHead(200, {
'Content-Type': 'text/html',
'Access-Control-Allow-Origin' : '*'});
這是您嘗試完成的功能的完整示例。 我在 hyperdev 而不是 jsFiddle 中創建了示例,以便您可以看到服務器端和客戶端代碼。
查看代碼: https : //hyperdev.com/#!/ project/ destiny-authorization
查看工作申請: https : //destiny-authorization.hyperdev.space/
此代碼為返回隨機字符串的 get 請求創建處理程序:
app.get("/string", function(req, res) {
var strings = ["string1", "string2", "string3"]
var n = Math.floor(Math.random() * strings.length)
res.send(strings[n])
});
這個 jQuery 代碼然后發出 ajax 請求並從服務器接收隨機字符串。
$.get("/string", function(string) {
$('#txtString').val(string);
});
請注意,此示例基於 Jamund Ferguson 的答案中的代碼,因此,如果您覺得這很有用,請務必也給他點贊。 我只是認為這個例子會幫助你了解一切是如何組合在一起的。
RESTful API(路由):
rtr.route('/testing')
.get((req, res)=>{
res.render('test')
})
.post((req, res, next)=>{
res.render('test')
})
AJAX 代碼:
$(function(){
$('#anyid').on('click', function(e){
e.preventDefault()
$.ajax({
url: '/testing',
method: 'GET',
contentType: 'application/json',
success: function(res){
console.log('GET Request')
}
})
})
$('#anyid').on('submit', function(e){
e.preventDefault()
$.ajax({
url: '/testing',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({
info: "put data here to pass in JSON format."
}),
success: function(res){
console.log('POST Request')
}
})
})
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.