使用 Node.js 进行基本 Ajax 发送/接收

发布于 2024-11-07 05:59:54 字数 1268 浏览 1 评论 0原文

因此,我正在尝试制作一个非常基本的 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);

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

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

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

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

(很抱歉这篇长篇多问题的文章,但各种教程和 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.

Here's the front end:

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;
}

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. 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.

  2. 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?

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

(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.)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

娇妻 2024-11-14 05:59:55

我遇到了以下代码错误(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' : '*'});

I was facing following error with code (nodejs 0.10.13), provided by ampersand:

origin is not allowed by access-control-allow-origin

Issue was resolved changing

response.writeHead(200, {"Content-Type": "text/plain"});

to

response.writeHead(200, {
                 'Content-Type': 'text/html',
                 'Access-Control-Allow-Origin' : '*'});
许仙没带伞 2024-11-14 05:59:55

这是您想要完成的功能的完整示例。我在 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 的答案中的代码,因此如果您发现这有用,请务必也给他投票。我只是认为这个例子可以帮助您了解所有内容是如何组合在一起的。

Here is a fully functional example of what you are trying to accomplish. I created the example inside of hyperdev rather than jsFiddle so that you could see the server-side and client-side code.

View Code:
https://hyperdev.com/#!/project/destiny-authorization

View Working Application: https://destiny-authorization.hyperdev.space/

This code creates a handler for a get request that returns a random string:

app.get("/string", function(req, res) {
    var strings = ["string1", "string2", "string3"]
    var n = Math.floor(Math.random() * strings.length)
    res.send(strings[n])
});

This jQuery code then makes the ajax request and receives the random string from the server.

$.get("/string", function(string) {
  $('#txtString').val(string);
});

Note that this example is based on code from Jamund Ferguson's answer so if you find this useful be sure to upvote him as well. I just thought this example would help you to see how everything fits together.

老街孤人 2024-11-14 05:59:54
  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");

前端(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()

  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.

  2. 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.

  3. 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");

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();
}

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.

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

铜锣湾横着走 2024-11-14 05:59:54

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)

https://expressjs.com

如果您在客户端使用 jQuery,您可以这样做像这样的东西:

$.get("/string", function(string) {
    alert(string)
})

Express makes this kind of stuff really intuitive. The syntax looks like below :

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)

https://expressjs.com

If you're using jQuery on the client side you can do something like this:

$.get("/string", function(string) {
    alert(string)
})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文