1

When Running my code this error pops up in the console!

XMLHttpRequest cannot load http://api.sportsdatallc.org/mlb-t5/games/2015/04/12/boxscore.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

This is my server.js file

var express = require('express');

var app = express();

app.use(express.static('public'));
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();
});
var server = app.listen(process.env.PORT || 3000, function (){
    console.log('### Server is listening on PORT: ', server.address().port);
});

I did some research and it showed used this line but im confused on where i put the express.static line also!

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

2 Answers2

1

like this

//CORS middleware
var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    next();
}
app.use(allowCrossDomain);

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

EDIT 1

ok, It's much of server side thing , if u don't have control on sportsdatallc.org domain u can't modify their headers and allow cross origin requests.

However if u r writing ur own server(if u own sportsdatallc.org ) which i thought earlier as u mentioned server.js , then u can put this cors logic to allow cross domain requests.

u can confirm if it's a cors issue by some live test servers like http://client.cors-api.appspot.com/client or https://httpbin.org/ depending on in which domain u host angular app .

Also I am not sure if it's completely correct but u can use a proxy kind of approach , you can put ur server in org domain and route all request through that , ofc in ur server u can allow cors ref http://www.w3.org/TR/cors/

Aishwat Singh
  • 4,331
  • 2
  • 26
  • 48
  • @ChrisManfredi from your angular code are u trying to hit localhost:3000/ or http://api.sportsdatallc.org/mlb-t5/games/2015/04/12/boxscore.json. – Aishwat Singh Nov 03 '15 at 10:16
  • possible duplicate of http://stackoverflow.com/questions/29547003/angularjs-no-access-control-allow-origin-header-is-present-on-the-requested-r – Aishwat Singh Nov 03 '15 at 10:19
  • I am trying too hit api.sportsdatallc.org – Chris Manfredi Nov 03 '15 at 20:41
  • @ChrisManfredi one more quick thing, https://wordnik-play-server.herokuapp.com is a cors enabled server , tested this and your url at http://client.cors-api.appspot.com/client , seems like later is not enabled. plz accept or upvote if it helps – Aishwat Singh Nov 03 '15 at 21:47
-1

HELP! Still confused on this topic!