Basically, I need to run a Node/Express server with json-server to mock a RESTFUL API for a test Angular app I'm developing. The issue is that Google Chrome is throwing an error indicating that I've run into a CORS issue. I've tried configuring my server in such a way as to address the CORS issue . . .
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();
});
. . . to no avail.
Is there anything more I could do without fiddling with JSONP or altering my Angular code in any way? It seems to work just fine on a Rails server.
Edit: As many have suggested, I've attempted to use the cors module to address the issue, but that doesn't seem to be working, either. Here's my server.js file:
var express = require('express');
var app = express();
var path = require("path");
var jsonServer = require("json-server");
var databaseServer = jsonServer.create();
var cors = require("cors");
app.use(cors());
app.use("/", express.static(__dirname));
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
var object = {
"fighters": [
{
"id": 1,
"firstName": "Jose",
"lastName": "Aldo",
"nickname": "Scarface",
"wins": 25,
"losses": 1,
"draws": 0,
"imageUrl": "/images/jose_aldo.png"
},
{
"id": 2,
"firstName": "Conor",
"lastName": "McGregor",
"nickname": "",
"wins": 17,
"losses": 2,
"draws": 0,
"imageUrl": "/images/conor_mcgregor.png"
}
]
};
databaseServer.use(jsonServer.defaults);
databaseServer.use(jsonServer.router(object));
databaseServer.listen(4000);
And here's my Angular service:
var FighterService = angular.module("FighterService", ["ngResource"]);
FighterService.factory("Fighter", ["$resource", function ($resource) {
return $resource("localhost:4000/fighters/:fighterId",
{ fighterId : "@id" },
{
query: {
method: "GET",
params: { fighterId: "@id" },
isArray: true
},
get: { method: "GET" }
});
}]);
SOLVED
The clue is in the error:
XMLHttpRequest cannot load localhost:4000/fighters.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.b
In your Angular, the line
return $resource("localhost:4000/fighters/:fighterId",
thinks you're referring to a URL with protocol "localhost:".
It should be an absolute HTTP URL:
return $resource("http://localhost:4000/fighters/:fighterId",
With the correct CORS support you already have, that works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With