2

I wrote very simple server :

/* Creating server */
var server = http.createServer(function (request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello World\n");
});

/*Start listening*/
server.listen(8000);

I run it using nodejs.

Now i want to write simple client that use ajax call to send request to server and print response (Hello World)

Here javascript of clinet:

$.ajax({
            type: "GET",
            url: "http://127.0.0.1:8000/" ,
            success: function (data) {
            console.log(data.toString);
            }
        });

When I open client html file i get following error in console:

XMLHttpRequest cannot load http://127.0.0.1:8000/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. 

I tried adding to ajax call following:

 $.ajax({
            type: "GET",
            url: "http://127.0.0.1:8000/" ,
            dataType: 'jsonp',
            crossDomain: true,
            success: function (data) {
            console.log(data.toString);
            }
        });

But then i get

Resource interpreted as Script but transferred with MIME type text/plain: "http://127.0.0.1:8000/?callback=jQuery211046317202714271843_1410340033163&_=1410340033164". 

Anyone can explain what i did wrong and perhaps how to fix it?

Many thanks!

Farseer
  • 4,036
  • 3
  • 42
  • 61

2 Answers2

7

To overcome the CORS, in your node.js file write the below, based on what you need:

// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');

// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
Hasan A Yousef
  • 22,789
  • 24
  • 132
  • 203
  • if you are interested, check this good post http://techslides.com/client-side-javascript-to-node-js, believe you may learn something new from it – Hasan A Yousef Jan 22 '15 at 13:26
3

The first error is caused by CORS (Cross Origin Resource Sharing) policy. It's rule by all browsers that you cannot make a request to a remote server in AJAX other than to the current server the script/page was loaded from unless that remote server allows it via Access-Control-Allow-Origin header.

I suggest serving the page from the same Node.js server. Then it will work. Example, when the request comes to root / page, then serve the index.html file, otherwise, server whatever other content you want.

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

/* Creating server */
var server = http.createServer(function (request, response) {
    if (request.url == '/' || request.url == '/index.html') {
        var fileStream = fs.createReadStream('./index.html');

        fileStream.pipe(response);
    } else {
        response.writeHead(200, {"Content-Type": "text/plain"});
        response.end("Hello World\n");
    }
});

/*Start listening*/
server.listen(8000);
esengineer
  • 9,514
  • 7
  • 45
  • 69
  • Thank you for the answer, But how i can send modified index.html to client, if for example content of index.html is dynamic and on every request it should be different? – Farseer Sep 10 '14 at 09:33
  • The example I've provided is very basic. It assumes your content is statically stored in a file. You can, of course, provide a dynamic content which may be based on some data from a remote server like a database or a remote Web service. All you have to do is to build the content dynamically. I suggest you to look into [Express](http://expressjs.com) Node.js framework which allows you to serve [template files](http://expressjs.com/guide.html#template-engines) where there are placeholders for dynamic content. Once you prepare the dynamic content, you can give it to the template engine. – esengineer Sep 10 '14 at 09:38
  • The template engine + Express will render your dynamic content properly and serve to the client. – esengineer Sep 10 '14 at 09:38