0

I made an html based on a course I was studying and was trying out post method using ajax. I made a web server using node js and hosted it on a port so that I can send a JSON file and receive it from there but it is always failing. This is my code on my html for the post method.

$.post('http://localhost:8000', message).done(function(received) {
  $('#output').text('You chose ' + received.value + ' out of ' + received.maxValue)
}).fail(function () {
  $('#output').text('Failed')
})

It is always failing, hope to get some ideas because I was studying html and just needed to make a quick server to test using post requests on.

It worked when I hosted the html on the node.js server on the same port. I am tying to see how to make it work while not being on the same port or server.

Here's my server side code:

var http = require('http'),
  fs = require('fs'),
  path = require('path')

var PORT = 8000

fs.readFile(path.resolve(__dirname, "index.html"), function(err, html) {
  if (err) {
    throw err;
  }
  http.createServer(function(request, response) {
    if (request.url == '/home') {
      response.writeHeader(200, {
        "Content-Type": "text/html"
      });
      response.write(html);
      response.end();
    }
    if (request.method == 'POST') {
      console.log('POST2')
      var body = ''
      request.on('data', function(data) {
        body += data
      });
      request.on('end', function() {
        try {
          var post = JSON.parse(body);
          console.log(post);
          response.writeHead(200, {
            'Content-Type': 'application/json'
          });
          response.write(JSON.stringify(post))
          response.end();
          return;
        } catch (err) {

          var post = JSON.parse(body);
          // deal_with_post_data(request,post);
          response.writeHead(200, {
            'Content-Type': 'application/json'
          });
          response.write(body);
          response.end();
          return;
        }
      });
    }

  }).listen(PORT);
});
console.log('Node.js web server at port ' + PORT + ' is running..')
mplungjan
  • 169,008
  • 28
  • 173
  • 236
drei
  • 1
  • 2
  • 1
    It's impossible to really help without seeing the server code, but: *"It worked when I hosted the html on the node.js server on the same port. I am tying to see how to make it work while not being on the same port or server."* If you look in the browser console, you'll probably see an error there that mentions CORS. It really should mention the [Same Origin Policy](http://en.wikipedia.org/wiki/Same_origin_policy) (CORS is a way to tell the browser to loosen the policy). The SOP and CORS are ***very*** thoroughly covered by previous questions and answers. – T.J. Crowder Feb 07 '23 at 14:51
  • The short version: You probably need to have the server reply to `OPTIONS` (a "preflight" request) with a response containing the necessary headers to allow a `POST` from your page's origin. You've mentioned Node.js -- if you're using Express, you probably want to use [the `cors` module](https://www.npmjs.com/package/cors). – T.J. Crowder Feb 07 '23 at 14:52
  • More: https://stackoverflow.com/questions/10636611/how-does-the-access-control-allow-origin-header-work – T.J. Crowder Feb 07 '23 at 14:52
  • Hi @drei, welcome to Stack Overflow! It would help if you could tell us a bit more about the request you are making from the browser. Is it successful? Is the payload wrong? What status code are you receiving? You may use your browser’s development tools to find out (most prominently the “Network” tab). – dulange Feb 07 '23 at 14:54
  • Thanks Ill try and research about it!! Sorry Its my first time hearing about CORS, just tried making a quick local server for my html : I'll be reading this in the mean while. – drei Feb 07 '23 at 14:57
  • "[failing](https://idownvotedbecau.se/itsnotworking/)" isn't really a helpful description of the problem. In what way does it fail? Use the browser's developer tools. Are any error messages show on the Console? The fail callback (`fail(function ()`) gets passed an argument (which you are ignoring) which should provide some information to help you debug this: Look at it! Also look at the Network tab. Do you see the request? And the response? What does the response look like? Does it have the expected HTTP status code? Content-Type? Response body? – Quentin Feb 07 '23 at 14:59
  • What is the value of `message`? Is it even JSON? – Quentin Feb 07 '23 at 15:01
  • Inside `request.on('end', function () {` you have a `try`/`catch` block … but the `catch` block (aside from a `console.log`) is identical to the `try` block, so if there is an error then you'll just **make the same error again**! – Quentin Feb 07 '23 at 15:03
  • I used develop tools and saw that the response cant be loaded, and it I saw CORS. Thanks for the ideas, im currently reading how to allow my html to access my server now... – drei Feb 07 '23 at 15:13
  • I was able to connect now by adding things to the header, read a bit about CORS, guess this will do for now. Thanks for the responses!!! – drei Feb 07 '23 at 15:28

0 Answers0