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

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

问题描述

我在Node.js上具有使用 Faker.js 的带有虚假用户数据的简单API

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

它看起来像这样:

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

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无法加载 http://localhost:3500/api/user .不 请求中存在"Access-Control-Allow-Origin"标头 资源.因此,不允许访问原始空".

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.

或使用jQuery AJAX:

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>

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

Tell me please how to fix this problem and why it happens. How to get JSON data from my API ?

问题是我的API在http://localhost:3500上并且HTML在GET请求上在http://localhost:8000上,但是 https://stackoverflow.com/a/36526208/6135469

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

推荐答案

您还可以启用 CORS ,而无需使用 CORS模块

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天全站免登陆