Node.Js error "No 'Access-Control-Allow-Origin' header is present on the requested"

37,825

Solution 1

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);

Solution 2

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.

Share:
37,825
L1ghtk3ira
Author by

L1ghtk3ira

I work mostly in front end web development as my main area of expertise. I love CSS and CSS animation as well as learning my new favourite OPEN GL for Android. The good thing about Open GL is it is greatly transferable between different languages. During my down time I like to play video games, currently playing Dishonored and Red Dead Redemption. If you need help with OpenGl or CSS Animation let me know and I would be glad to help out!

Updated on February 02, 2021

Comments

  • L1ghtk3ira
    L1ghtk3ira over 3 years

    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.