Gregory-Turtle
Gregory-Turtle

Reputation: 1717

Unable to make post request to Node server

I am building a simple server using Node JS. I am using express for routing. I wanted to test post requests using JQuery, but I have been unable to succeed. I looked up the issue and many responses mentioned a cross-origin issue. I followed every piece of advice on the subject, but I am still unable to make it work. Here is my server code:

var express=require("express");
var app=express();
var cors = require('cors')
app.use(cors());
var bodyParser = require('body-parser-json')
app.use(bodyParser.json())

var allowCrossDomain = function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    next();
}

app.use(allowCrossDomain);

app.post('/', function(req, res, next) {
    console.log(req.body.base);
});

app.get('/', function(req, res) {
    console.log("ok");
});

/*Run the server.*/
app.listen(3000,function(){
    console.log("Working on port 3000");
});

I have tried using the core module and also manually enabling CORS. Still nothing.

Here is my front end test code:

function makePost() {
    $.post( "secret.compute.amazonaws.com:3000/", { base: "Hello" })
    .done(function( data ) {
        alert( "Got it" );
    })
    .fail(function( err ) {
        console.log(err);
    });
}

Finally, here is the error I get when the post fails:

[Exception... "" nsresult: "0x805e0006 ()" location: "JS frame :: file:///Users/my_name/Documents/Development/Origin/FrontEndTest/jquery.js :: .send :: line 4" data: no]

Any ideas as to what is going on?

Upvotes: 2

Views: 340

Answers (1)

Krzysztof Sztompka
Krzysztof Sztompka

Reputation: 7204

On server you have to set response in your route methods. Otherwise client side will wait for it and finally crash.

in server file change your routes to this code:

app.post('/', function(req, res, next) {
  console.log(req.body.base);
  res.end();
});

app.get('/', function(req, res) {
  console.log("ok");
  res.end();
});

You can also send some response data from server, if yes, then change res.end() to res.send("some response");

Upvotes: 3

Related Questions