如何使用 jQuery.getJSON 从本地主机上的 API 获取 JSON 数据 [英] How to GET JSON data from my API on localhost with jQuery.getJSON

查看:30
本文介绍了如何使用 jQuery.getJSON 从本地主机上的 API 获取 JSON 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Node.js 上有简单的 API,使用

但是当我尝试使用 jQuery 获取这些数据时:

<头><meta charset="UTF-8"><title></title><script type="text/javascript" src="bower_components/jquery/dist/jquery.js"></script><身体><script type="text/javascript">$.getJSON('http://localhost:3500/api/user').done(function(data) {控制台日志(数据)})</html>

我在控制台中收到以下错误:

<块引用>

XMLHttpRequest 无法加载

或使用 jQuery AJAX:

<头><meta charset="UTF-8"><title></title><script type="text/javascript" src="bower_components/jquery/dist/jquery.js"></script><身体><script type="text/javascript">$.ajax({url: "http://localhost:3500/api/user",jsonp: "回调",数据类型:jsonp",成功:功能(数据){控制台日志(数据);}});</html>

请告诉我如何解决这个问题以及它为什么会发生.如何从我的 API 获取 JSON 数据?

问题是我的 API 在 http://localhost:3500 和 HTML 上,在 http://localhost:8000 上有 GET 请求,但是 CORS 不支持.我写了这个问题的答案,解决了这个问题https://stackoverflow.com/a/36526208/6135469

解决方案

您还可以启用 CORS 不使用 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");下一个();});

因此,代码看起来像这样

var express = require('express'),app = express(),faker = require('faker');app.set('port', process.env.PORT || 3500);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");下一个();});app.get('/api/user', function(req, res) {res.json({名称:faker.name.findName(),电子邮件:faker.internet.email(),地址:faker.address.streetAddress(),生物:faker.lorem.sentence(),图片:faker.image.avatar()});});var server = app.listen(app.get('port'), function() {console.log('服务器启动:http://localhost:' + app.get('port'));});

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="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 http://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="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 https://stackoverflow.com/a/36526208/6135469

解决方案

You can also enable CORS without using the CORS Module

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

Therefore, the code would look like this

var express = require('express'),
    app = express(),
    faker = require('faker');

app.set('port', process.env.PORT || 3500);

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

var server = app.listen(app.get('port'), function() {
    console.log('Server up: http://localhost:' + app.get('port'));
});

这篇关于如何使用 jQuery.getJSON 从本地主机上的 API 获取 JSON 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆