使用node.js发送/接收基本Ajax

Dan*_*ill 55 javascript ajax 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;
}
Run Code Online (Sandbox Code Playgroud)

这应该将请求发送到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);
Run Code Online (Sandbox Code Playgroud)

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

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

  2. 我对如何在localhost上调用此页面感到困惑.前端名为index.html,服务器发布到8001.在初始化server.js后,我应该在localhost上访问初始html页面的地址是什么?我应该改为.listen(index.html)或类似吗?

  3. 我是如何实现这个(使用.responsetext等)有其他明显的问题吗?

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

amp*_*and 62

  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'模块来解析请求.

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

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

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

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");
Run Code Online (Sandbox Code Playgroud)

前端(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();
}
Run Code Online (Sandbox Code Playgroud)

您需要熟悉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()的!!!


Jam*_*son 29

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)
Run Code Online (Sandbox Code Playgroud)

http://expressjs.com/guide.html

如果你在客户端使用jQuery,你可以这样做:

$.get("/string", function(string) {
    alert(string)
})
Run Code Online (Sandbox Code Playgroud)


the*_*eme 5

我正面临跟随错误的代码(nodejs 0.10.13),由&符号提供:

access-control-allow-origin不允许使用origin

问题已经解决了

response.writeHead(200, {"Content-Type": "text/plain"});
Run Code Online (Sandbox Code Playgroud)

response.writeHead(200, {
                 'Content-Type': 'text/html',
                 'Access-Control-Allow-Origin' : '*'});
Run Code Online (Sandbox Code Playgroud)