Ad

How Can I Fix This Cors Error With Cors Module

- 1 answer

I installed cors module and coded like below.

var express = require('express'),
    favicon = require('serve-favicon'),
    cors = require('cors');
var app = express();

if (app.get('env') === 'development') {
    app.locals.pretty = true;
}

app.set('view engine', 'pug');
app.set('views', './views');

app.use(express.static(__dirname + '/public'));
app.use(favicon(__dirname + '/public/img/logo.ico'));
app.use(cors());

app.get('/', (req, res) => {
    res.render('view');
});

app.listen(80, () => {
    console.log('Server started on port 80');
});

After this I turned on server and tried to access files on server by this code.

$.getJSON('https://server.domain/global.json', data => {
    console.log(data);
});

But It makes error.

I can access to js files but not json file.

enter image description here

What's the problem?

[+Edit] I can get js files by

$.getScript('~/js/file.js');

But not by

$.get('~/js/file.js');
Ad

Answer

I finally solved this problem with code below.

app.all('/*', function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    next();
});
Ad
source: stackoverflow.com
Ad