简体   繁体   English

使用node.js和express处理POST请求

[英]Using node.js and express to process a POST request

I am new to learning AJAX and new to web development at all, and I am having trouble having my local server and my remote server process a post request. 我是刚接触AJAX的新手,也不是Web开发的新手,并且我无法让本地服务器和远程服务器处理发布请求。 I am using node.js and the express module. 我正在使用node.js和express模块​​。

Here is the code of my server: 这是我的服务器的代码:

var express = require('express');

//start server
var app = express.createServer();

//handle requests
app.post('/hello', function(req, res){
    res.send("hello");
});

app.listen(8888);

Pretty basic, I know. 很基本,我知道。 To test this, I create an XMLHttpRequest manually through the console in Chrome (I have disabled the Cross-Origin policy to test on my local machine): 为了对此进行测试,我通过Chrome中的控制台手动创建了XMLHttpRequest(我已禁用跨域策略以在本地计算机上进行测试):

var xhr = new XMLHttpRequest();
xhr.open('POST', 'localhost:8888/hello', true);
xhr.send('name=me'); //body of request is irrelevant at this point

When I send the request to my local machine, it returns immediately and says it failed. 当我将请求发送到本地计算机时,它立即返回并说失败。 When I send the request to my remote server (where localhost is replaced by my server's IP) I don't get the error in my console, but when I check the xhr object's status is failed. 当我将请求发送到远程服务器(其中localhost被服务器的IP替换)时,在控制台中没有出现错误,但是当我检查xhr对象的状态失败时。

I don't know whether the problem is with the way my server is written, or the way I am sending the request to the server. 我不知道问题出在我的服务器编写方式还是向服务器发送请求的方式。 However, I have been looking at tutorials and examples that show express processing post requests like I do above, and other tutorials that show sending POST requests like I do above. 但是,我一直在看一些教程和示例,这些教程和示例显示了像我上面那样处理后处理的请求,以及其他一些教程,它们像上面一样显示了发送POST请求的过程。

Sending and processing GET requests seems to work fine. 发送和处理GET请求似乎正常。 I must be missing something. 我肯定错过了什么。

Thanks, Xaan. 谢谢,Xaan。

发出POST时,您需要在URL中包括HTTP:

xhr.open('POST', 'http://localhost:8888/hello', true);

XHR does not work if the calling js is not served by a webserver. 如果Web服务器未提供调用js,则XHR不起作用。

What you should do is add a simple route on your Express server 您应该做的是在Express服务器上添加一条简单的路由

app.get('/', function( req, res) {
  res.sendfile('index.html');
})

Where index.html contains your testing code. 其中index.html包含您的测试代码。

If you want to test from a different webserver and be confronted with the annoying Cross-Origin policy you can also use this super usefull command to spawn a webserver in your current folder: 如果要从其他Web服务器进行测试并遇到恼人的跨域策略,则还可以使用以下超级有用的命令在当前文件夹中生成Web服务器:

python -m SimpleHTTPServer

I use it so often that I actually alias it: 我经常使用它,因此实际上给它起别名:

alias www='python -m SimpleHTTPServer'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM