3

I am coding a simple app with html and node.js It is my first app by node.js, javascript and html

By node I want send a json, when a url is called (In my local machine the below ip is called : 127.0.0.1/local)

when I call that address, the expected info returned to browser correctly. Also I added a button in my html page and need to call above address, to get JSON data.

I have tried the solution of accepted answer at here

but I got this error:

XMLHttpRequest cannot load http://127.0.0.1/local Origin server is not allowed by Access-Control-Allow-Origin node.js

What is problem? I think the provided information is completed, but if it is not, let me know to share my code.

  • Update

Ok, I see I need to explain my exact target and provide my code;

I am developing a program by Node.js I have a mysql database which I want to get some info from db and show on html page. I use bookshelf, express, lodash, router on my database js file so I get data from db by calling

127.0.0.1:3002/local

I have a button on my html page; and need to get info when user touch it. My html page is running on

127.0.0.1:8080

So I think there is no need to provide Access, both of db and html is running on one server.

Maybe my solution to call db data by XMLHttpRequest is not a right solution. I am asking is it only way to call data or not?

Community
  • 1
  • 1
Fa.Shapouri
  • 988
  • 2
  • 12
  • 30

2 Answers2

1

Your page and your Json resource are on 2 differents ports (3002 and 8080). This is what cause the Access-Control-Allow-Origin error. it as as security of the browser against cross-scripting.

In ajax, in normal case, you should have the same origin for the page and the resources, and the same origin policy rely on the hostname AND the port.

The solution for you is simply to access your main page and the JSON resource on the same port.

  • 127.0.0.1:8080/index.html -> get your main page.
  • 127.0.0.1:8080/local -> gets your JSON

There is not problem by accessing it with XMLHttpRequest , this is the right way to do, and is used by many framework, like angular for example.

pdem
  • 3,880
  • 1
  • 24
  • 38
0

Have you try to add headers in your node js file.If not then add below code:

app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
 res.header("Access-Control-Allow-Headers", "Origin, __setXHR_, X-Requested-With, Content-Type, user-agent, Accept, X-Auth-Token, X-Amz-Content,Authorization");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
next();
});
Mital Gajjar
  • 244
  • 1
  • 6
  • Thanks Mital, I don't try your solution, I prefer to use cors node package, I don't mark your answer as useful, because CORS package is better way for me – Fa.Shapouri Nov 28 '16 at 16:11