使用 node.js 进行基本 Ajax 发送/接收 [英] Basic Ajax send/receive with node.js

查看:49
本文介绍了使用 node.js 进行基本 Ajax 发送/接收的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在尝试制作一个非常基本的 node.js 服务器,它接收一个字符串请求,从数组中随机选择一个并返回选定的字符串.不幸的是,我遇到了一些问题.

So I'm trying to make a very basic node.js server that with take in a request for a string, randomly select one from an array and return the selected string. Unfortunately I'm running into a few problems.

这是前端:

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:

This should send the request to 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);

很明显,这里有几个问题:

So clearly there are several things going wrong here:

  1. 我感觉我连接"这两个文件的方式在 xmlhttp.open 方法和使用 response.on 方法中都不正确> 将字符串发送回前端.

  1. I get the feeling the way I am "connecting" these two files isn't correct both in the xmlhttp.open method and in using response.on to send the string back to the front end.

我对如何在本地主机上调用此页面感到有些困惑.前端命名为 index.html,服务器发布到 8001.在我初始化 server.js 之后,我应该在 localhost 上访问哪个地址才能访问初始 html 页面?我应该将其更改为 .listen(index.html) 或类似的内容吗?

I'm a little confused with how I call this page on localhost. The front end is named index.html and the sever posts to 8001. What address should I be go to on localhost in order to access the initial html page after I have initialized server.js? Should I change it to .listen(index.html) or something like that?

我的实现方式是否还有其他明显的问题(使用 .responsetext 等)

are there other obvious problems with how I am implementing this (using .responsetext etc.)

(抱歉,这篇多问题的帖子太长了,但各种教程和 node.js 源代码都假设用户已经了解这些内容.)

(sorry for the long multi-question post but the various tutorials and the node.js source all assume that the user already has an understanding of these things.)

推荐答案

  1. 您的请求应该发送到服务器,而不是实例化它的 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' 模块来解析请求.

  1. Your request should be to the server, NOT the server.js file which instantiates it. So, the request should look something like this: xmlhttp.open("GET","http://localhost:8001/", true); Also, you are trying to serve the front-end (index.html) AND serve AJAX requests at the same URI. To accomplish this, you are going to have to introduce logic to your server.js that will differentiate between your AJAX requests and a normal http access request. To do this, you'll want to either introduce GET/POST data (i.e. call http://localhost:8001/?getstring=true) or use a different path for your AJAX requests (i.e. call http://localhost:8001/getstring). On the server end then, you'll need to examine the request object to determine what to write on the response. For the latter option, you need to use the 'url' module to parse the request.

您正确地调用了 listen() 但错误地编写了响应.首先,如果您希望在导航到 http://localhost:8001/ 时提供 index.html,您需要使用 response.write()response.end() 将文件的内容写入响应.首先,您需要包含 fs=require('fs') 以访问文件系统.然后,您需要实际提供文件.

You are correctly calling listen() but incorrectly writing the response. First of all, if you wish to serve index.html when navigating to http://localhost:8001/, you need to write the contents of the file to the response using response.write() or response.end(). First, you need to include fs=require('fs') to get access to the filesystem. Then, you need to actually serve the file.

XMLHttpRequest 需要指定一个回调函数,如果您异步使用它(第三个参数 = true,正如您所做的那样)并且想要对响应做一些事情.按照您现在的方式,string 将是 undefined(或者可能是 null),因为该行将在 AJAX 请求完成之前执行(即 responseText 仍然是空的).如果同步使用(第三个参数=false),就可以像以前一样编写内联代码.不建议这样做,因为它会在请求期间锁定浏览器.异步操作通常与 onreadystatechange 函数一起使用,一旦完成就可以处理响应.您需要学习 XMLHttpRequest 的基础知识.从此处开始.

XMLHttpRequest needs a callback function specified if you use it asynchronously (third parameter = true, as you have done) AND want to do something with the response. The way you have it now, string will be undefined (or perhaps null), because that line will execute before the AJAX request is complete (i.e. the responseText is still empty). If you use it synchronously (third parameter = false), you can write inline code as you have done. This is not recommended as it locks the browser during the request. Asynchronous operation is usually used with the onreadystatechange function, which can handle the response once it is complete. You need to learn the basics of XMLHttpRequest. Start here.

这是一个包含上述所有内容的简单实现:

Here is a simple implementation that incorporates all of the above:

server.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 的一部分):

frontend (part of 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 是一个不错的起点.

You will need to be comfortable with AJAX. Use the mozilla learning center to learn about XMLHttpRequest. After you can use the basic XHR object, you will most likely want to use a good AJAX library instead of manually writing cross-browser AJAX requests (for example, in IE you'll need to use an ActiveXObject instead of XHR). The AJAX in jQuery is excellent, but if you don't need everything else jQuery offers, find a good AJAX library here: http://microjs.com/. You will also need to get comfy with the node.js docs, found here. Search http://google.com for some good node.js server and static file server tutorials. http://nodetuts.com is a good place to start.

更新:我已将上面代码中的 response.sendHeader() 更改为新的 response.writeHead() !!!

UPDATE: I have changed response.sendHeader() to the new response.writeHead() in the code above !!!

这篇关于使用 node.js 进行基本 Ajax 发送/接收的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆