Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js, express and different ports

I've been playing with node.js and then came across the express framework. I can't seem to get it to work when different ports are being used.

I have my ajax on http://localhost:8888 which is a MAMP server I'm running on my Mac.

$.ajax({
    url: "http://localhost:1337/",
    type: "GET",
    dataType: "json",
    data: { }, 
    contentType: "application/json",
    cache: false,
    timeout: 5000,
    success: function(data) {
        alert(data);
    },
    error: function(jqXHR, textStatus, errorThrown) {
        alert('error ' + textStatus + " " + errorThrown);
    }
});

As you can see my node.js server is running on http://localhost:1337/. As a result nothing is getting returned and it's throwing an error.

Is there a way around this?

Thanks

Ben

like image 406
Ben Sinclair Avatar asked Apr 22 '12 08:04

Ben Sinclair


People also ask

What ports can I use for Express?

Node. js/Express. js App Only Works on Port 3000.

How do I use multiple ports in NodeJS?

Here is the sample code: var http=require('http'); var url = require('url'); var ports = [7006, 7007, 7008, 7009]; var servers = []; var s; function reqHandler(req, res) { var serPort=req. headers. host.

What ports can I use for NodeJS?

Port 80 is the standard HTTP port (unencrypted web connection). Port 443 is the TLS/SSL port (HTTPS - encrypted connection).

What is the difference between NodeJS and Express?

NodeJS is an event-driven, non-blocking I/O model using JavaScript as its main language. It helps to build scalable network applications. Express is a minimal and flexible Node. js web application framework that provides a robust set of features for web and mobile applications.


1 Answers

The problem you have is that you are trying to make a cross-origin request and that's not allowed by browsers (yes, the same hostname with a different port counts as a different origin for this purpose). You have three options here:

1. Proxy the request.

Do this one if you can. Write some code that runs on the :8888 server that proxies requests to the 1337 one. You can also do this by sticking a proxy in front of both of them, something like Nginx is pretty good at this and easy to set up

2. Use CORS (Cross Origin Resource Sharing)

See: http://en.wikipedia.org/wiki/Cross-origin_resource_sharing and https://developer.mozilla.org/en/http_access_control

This means adding some headers to your responses to tell the browser that cross-origin requests are ok here. In your Express server add middleware like this:

  function enableCORSMiddleware (req,res,next) {
     // You could use * instead of the url below to allow any origin, 
     // but be careful, you're opening yourself up to all sorts of things!
     res.setHeader('Access-Control-Allow-Origin',  "http://localhost:8888");
     next()
  }
 server.use(enableCORSMiddleware);

3. Use JSONP

This is a trick where you encode your "AJAX" response as Javascript code. Then you ask the browser to load that code, the browser will happily load scripts cross-origin so this gets round the cross-origin issue. It also lets anyone else get round it as well though, so be sure that's what you want!

On the server side you need wrap your response in a Javascript function call, express can do this for automatically if you enable the "jsonp callback" option like this:

server.enable("jsonp callback");

Then send your response using the "json()" method of response:

server.get("/ajax", function(req, res) {
    res.json({foo: "bar"});
});

On the client side you can enanble JSONP in jQuery just by changing "json" to "jsonp" in the dataType option:

dataType: "jsonp", 
like image 65
Thomas Parslow Avatar answered Oct 21 '22 01:10

Thomas Parslow