Node.Js error "No 'Access-Control-Allow-Origin' header is present on the requested"
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);
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.