7

This question is similar to others; however there is a difference that makes it very confusing why it is not working.

My JavaScript was calling 6 json files and all worked correctly. In Node.JS I have cors and headers set up as shown below:

var fs = require('fs');
var http = require("https");
var express = require('express');
var app = express();
var path = require('path');
var http = require("http");
var url = require("url");
var req = require('request')
var pem = require('pem');
var cors = require("cors");

app.use(express.static(path.join(__dirname, '../')));

app.listen(process.env.PORT || 8080);

app.options('*', cors()); 

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-  With, Content-Type, Accept");
    next();   
});

app.all('/posts', function(req, res){
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
});

app.get('/', function (req, res) { 
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); 
    res.writeHead(200, {'Content-Type': 'text/plain'});
    contents = fs.readFileSync("sliderImages.json", "utf8");
    console.log(path.join(__dirname, '/sliderImages.json'));
    res.end(contents);
});

All 6 json files are grabbed from the absolute URL path by Node JS. I have made 2 more yesterday and everything was working fine. However, today I made one and implemented the same way and received the following error:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

I am implementing each the same way, example:

var base_url = 'http://127.0.0.1:8080';

mainInformationTop();

function mainInformationTop()
{
    $.ajax({
        type: "GET", 
        url: base_url + "/api/topInformation.json", 
        dataType: "json",
        success: function(response)
        {
            var json_obj = response.mainDescription;
            var imagesSlider="";
            var imagesSliderDescription ="";
            for (var i = 0; i< json_obj.length; i++) 
            {

            }

        }
        , 
        error: function(jqXHR, textStatus, errorThrown) {
            alert(jqXHR.status);
        }  
    })    
}

I don't think the json file is relevant but below is my json file:

{"mainDescription":[
{
"display": "my display",
"description" : "my description"
}
]}

I have took out the information in the for loop for testing as well as my append because irrelevant. For some reason it fails and goes to error instead of success. All other calls are set up the same way and work correctly.

halfer
  • 19,824
  • 17
  • 99
  • 186
L1ghtk3ira
  • 3,021
  • 6
  • 31
  • 70
  • I tried that, plus all the others work fine. – L1ghtk3ira May 26 '16 at 16:05
  • 2
    @User555: Why? The server doesn't seem to generate JSONP. – Felix Kling May 26 '16 at 16:06
  • Switching to jsonP makes them all fail – L1ghtk3ira May 26 '16 at 16:06
  • I think just type json is fine since I do not need callbacks. And the rest all work with just json as well – L1ghtk3ira May 26 '16 at 16:08
  • You should NOT use `readFileSync` in `app.get`. (But that doesn't solve your issue.) You sure it should be named `/postss` instead of `/posts`? (Changing that might not solve the issue either.) Do you run this from local file in a browser instead of from a local server? That maybe explains the origin "null"? – CFrei May 26 '16 at 16:09
  • See here: [XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin](http://stackoverflow.com/questions/3595515/xmlhttprequest-error-origin-null-is-not-allowed-by-access-control-allow-origin) – CFrei May 26 '16 at 16:09
  • @CFrei sorry that was typo when formatting i will fix. – L1ghtk3ira May 26 '16 at 16:10
  • 1
    @User555 that makes absolutely no sense. do you know what JSONP is? – Kevin B May 26 '16 at 16:12
  • Yes it used to bypass cross domains. But it doesnt work with that and worked with json – L1ghtk3ira May 26 '16 at 16:13
  • @L1ghtk3ira sorry for confusion, wasn't meaning you. but, in your $.ajax, you're requesting data from a .json file, that's a static file in your static directory right? – Kevin B May 26 '16 at 16:14
  • Yes I have all those files in a static directory. – L1ghtk3ira May 26 '16 at 16:15
  • you don't seem to be setting cors headers for those files. – Kevin B May 26 '16 at 16:15
  • I don't fully follow I am new to cors. I have this app.options('*', cors()); And the other 6 worked fine so I don't understand why this would fail one 1 new one now. If you do know the answer please provide an answer so if it works I can mark it correct. – L1ghtk3ira May 26 '16 at 16:17
  • The other 6 files are also static files? the .options() setting only fixes requests that require a preflight, a plain .get to a static file doesn't require a preflight. – Kevin B May 26 '16 at 16:17
  • Also I don't understand why people are down voting when its a valid question. – L1ghtk3ira May 26 '16 at 16:17
  • Probably because this question comes up every day, and the problem is always the same: the cors headers aren't set. I understand you're trying to set them, but, you haven't been successful yet. `app.use(cors());` according to the documentation. – Kevin B May 26 '16 at 16:19
  • Any tips or an answer you can provide? Sorry if it's duplicate I did not notice that it is probably the same. – L1ghtk3ira May 26 '16 at 16:20
  • Does this seem like the right track app.use(cors({origin: 'http://localhost:8080'}));? – L1ghtk3ira May 26 '16 at 16:23
  • you shouldn't need the {origin: part, unless you wanted to limit it down to only your app being able to access it from the browser (won't stop other servers from doing it though when you put the server in the wild) – Kevin B May 26 '16 at 18:00

4 Answers4

25

This is a much more simple version of this answer which achieves the same effect:

var fs = require('fs');
var express = require('express');
var cors = require('cors');

var app = express();

app.use(cors()); 
app.use(express.static(path.join(__dirname, '../')));

app.get('/', function (req, res) { 
  res.writeHead(200, {'Content-Type': 'text/plain'});
  contents = fs.readFileSync('sliderImages.json', 'utf8');
  res.end(contents);
});

app.listen(process.env.PORT || 8080);
Community
  • 1
  • 1
Chris Foster
  • 2,639
  • 2
  • 23
  • 30
4

Fixed it.

var fs = require('fs');
var http = require("https");
var express = require('express');
var app = express();
var path = require('path');
var http = require("http");
var url = require("url");
var req = require('request')
var pem = require('pem');
var cors = require("cors");

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});
app.use(express.static(path.join(__dirname, '../')));

app.listen(process.env.PORT || 8080);

app.options('*', cors()); 

app.all('/*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "http://localhost:8080");
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header("Access-Control-Allow-Headers", "X-Requested-With,     Content-Type");
    next();
});

app.get('/', function (req, res) { 
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); 
    res.writeHead(200, {'Content-Type': 'text/plain'});
    contents = fs.readFileSync("sliderImages.json", "utf8");
    console.log(path.join(__dirname, '/sliderImages.json'));
    res.end(contents);
 });

Despite what the comments said the only real thing I changed was moving the app.use before everything else. This solved the issue.

L1ghtk3ira
  • 3,021
  • 6
  • 31
  • 70
  • This is a bad solution because there is *way* too much duplicated code.... you can really achieve all of this with just one line using the `cors` module... – Chris Foster Aug 25 '16 at 17:04
  • @Chris I tried his solution and it works. If you can show a better example with explanations (and it works ) I will mark yous right instead. – L1ghtk3ira Aug 25 '16 at 18:38
  • I marked it right. How do you send a link to a specific answer by the way? That looks very useful. Thanks – L1ghtk3ira Aug 26 '16 at 02:16
  • You can click the 'Share' link in the bottom left of each answer, and use standard [markdown links](http://stackoverflow.com/editing-help) – Chris Foster Aug 26 '16 at 18:54
1

Install cors

npm install cors --save

Write this code in your app.js

const cors = require('cors');
const express = require('express');
let app = express();
app.use(cors());
app.options('*', cors()); //put this before your route 
keedy
  • 81
  • 2
  • 7
0

I also suffer this problem the code was as same as above but we want to put the code in starting point. dont put this code in last that means before (res.end()) sending response to client. Three methods (GET,POST,HEAD) that allowed you when you put this code anywhere i think but for other method try this and try with other modules like cors,express but i used http module only

var server=http.createServer(function (req, res) {

res.setHeader("Access-Control-Allow-Origin","*");
res.setHeader("Access-Control-Allow-Methods","PUT,GET,DELETE,PATCH")
res.setHeader('Access-Control-Allow-Credentials', true)
res.setHeader('Access-Control-Allow-Headers','X-Requested-With,content-type,Origin,Accept,Authorization')
// your other code followes