Reputation: 992
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. I am using node.js and the express module.
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):
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.
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.
Sending and processing GET requests seems to work fine. I must be missing something.
Thanks, Xaan.
Upvotes: 0
Views: 1324
Reputation: 26700
You need to include HTTP in your URL when you issue the POST:
xhr.open('POST', 'http://localhost:8888/hello', true);
Upvotes: 2
Reputation: 6339
XHR does not work if the calling js is not served by a webserver.
What you should do is add a simple route on your Express server
app.get('/', function( req, res) {
res.sendfile('index.html');
})
Where index.html contains your testing code.
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:
python -m SimpleHTTPServer
I use it so often that I actually alias it:
alias www='python -m SimpleHTTPServer'
Upvotes: 1