I have a node app built using express and I've been trying for ages to send an ajax post request to the node server. However despite reading many answers to similar problems here I struggled to come to grips with even what files I should be editing. For a long time i was trying to use http.createServer in one of the routes.js files. This of course meant I could not run the server on the same port as the app as there was already a server instantiated in the bin -> www file. So this morning I edited the bin www file so that it would log a message when data was sent to it. However despite this function having worked when I tested it on a second server, the response no longer fires when i added it so the same function to the server in the bin-> www file. In fact I don't even think my ajax request is reaching the server anymore. Just to be clear the ajax request is written in script.js which is a client file in the public folder and is being sent to the node server which is instantiated in the bin -> www file. Here's my code:
***bin -> www file***
var http = require('http');
var util = require('util')
var server = http.createServer(app,function (req, res) {
console.log('Request received: ');
util.log(util.inspect(req))
util.log('Request recieved:
method: ' + req.method + '
url: ' + req.url)
res.writeHead(200, { 'Content-Type': 'text/plain' });
req.on('data', function (chunk) {
console.log('GOT DATA!');
got = chunk.toString(data);
console.log(got)
});
res.end();
}).listen(3000);
console.log('Server running on port 3000')
***Script.js -> Client File***
$.ajax({
url: 'http://localhost:3000',
data: '{"abcdefghijklmnopqrstuvwxyz": ""}',
type: 'POST',
success: function (data) {
var ret = jQuery.parseJSON(data);
console.log(ret)
console.log('Success: ')
},
error: function (xhr, status, error) {
console.log('Error: ' + status);
},
});
Please Help! Thanks so much :)