How to GET JSON data from my API on localhost with jQuery.getJSON
I have simple API on Node.js with fake user data using
Faker.js
var express = require('express'),
app = express(),
faker = require('faker');
app.set('port', process.env.PORT || 3500);
var router = new express.Router();
router.get('/api/user', function(req, res) {
res.json({
name: faker.name.findName(),
email: faker.internet.email(),
address: faker.address.streetAddress(),
bio: faker.lorem.sentence(),
image: faker.image.avatar()
});
});
app.use('/', router);
var server = app.listen(app.get('port'), function() {
console.log('Server up: http://localhost:' + app.get('port'));
});
it looks like this:
but when I’m trying to get this data using jQuery:
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="https://reddit.fun/473116/bower_components/jquery/dist/jquery.js"></script>
</head>
<body>
<script type="text/javascript">
$.getJSON('http://localhost:3500/api/user').done(function(data) {
console.log(data)
})
</script>
</body>
</html>
I get the following error in the console:
XMLHttpRequest cannot load
localhost:3500/api/user
. No
‘Access-Control-Allow-Origin’ header is present on the requested
resource. Origin ‘null’ is therefore not allowed access.
or with jQuery AJAX:
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="https://reddit.fun/473116/bower_components/jquery/dist/jquery.js"></script>
</head>
<body>
<script type="text/javascript">
$.ajax({
url: "http://localhost:3500/api/user",
jsonp: "callback",
dataType: "jsonp",
success: function(data) {
console.log(data);
}
});
</script>
</body>
</html>
Tell me please how to fix this problem and why it happens. How to get JSON data from my API ?
Edit:
The problem was that my API is on
http://localhost:3500
and HTML with GET Request on
http://localhost:8000
but
CORS
has not supported. I write answer for this question in which this problem is solved
stackoverflow.com/a/36526208/6135469
Read more here: Source link