【问题标题】:jQuery AJAX to access REST API JSON datajQuery AJAX 访问 REST API JSON 数据
【发布时间】:2016-10-26 07:03:33
【问题描述】:

我在 http://localhost:3000/api/kfc 上的 node.js、express.js 应用程序中创建了一个 REST API。上面有 JSON 数据。创建它的函数...

router.get('/kfc', function(req, res, next) {
var response=
{
"id":"123", 
"name":"name1",
"drink":"drink1"
}
res.end(JSON.stringify(response));
});

我正在使用来自 http://localhost:8887/kfc.html 的 jQuery AJAX GET 调用来访问它,kfc.html 和 kfcLoad.js 的代码是-

//kfc.html

<html>
<body>
<h3>Order Placed</h3>
<ul id="ulOrder">

<script src="javascripts/jQuery.js"></script>
<script src="javascripts/kfcLoad.js"></script>
</body>    
</html>

//kfcLoad.js

$(function(){

var $ulOrder=$('#ulOrder');

function addOrder(order)
{
    $ulOrder.append('<li><strong>ID</strong>: '+ order.id+'<br><strong>Name</strong>: '+ order.name+'<br><strong>Drink</strong>: '+order.drink+'<br></li>');
}
$.ajax({
    type: 'GET',
    url: 'http://localhost:3000/api/kfc',
    dataType: 'jsonp',
    success: function(orders){

        $.each(orders, function(i, order){
        addOrder(order);
        });
    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.log(textStatus, errorThrown);
    }
});
});

我遇到错误-

jQuery.js:1 Uncaught SyntaxError: Unexpected token <
kfcLoad.js:1 Uncaught SyntaxError: Unexpected token <

【问题讨论】:

  • json 和 jsonp 不是一回事。您收到的错误表明您也没有收到,而是很可能是返回 html 的错误页面。
  • 不要使用JSON.stringify,只需使用res.json(response)
  • HTML 页面被渲染,但 json 数据没有显示在上面。我不确切知道 jsonp 是什么,但我在某处阅读时正在使用它,以使用 dataType: 'jsonp' 作为从另一个端口访问的解决方案。当我不使用 jsonp 时,我收到了这个错误-XMLHttpRequest cannot load http://localhost:3000/api/kfc. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
  • @eblin 它仍然给出这些错误。
  • 在使用它之前研究一下jsonp是什么...... wtf

标签: jquery json ajax node.js rest


【解决方案1】:

应该在您的 API 服务器上启用 CORS 以便从另一个端口进行访问。如果您使用Express.js 启用此功能,您可以使用https://www.npmjs.com/package/cors 模块

如何:

npm install cors

然后改变你的

router.get('/kfc', function(req, res, next) {

router.get('/kfc', cors(), function(req, res, next) {

也可以改用 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");
    next();
});

并将dataType: 'jsonp' 更改为dataType: 'json'

例子:

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

app.get('/kfc', cors(), function(req, res, next) {
    var response = {
        "id": "123",
        "name": "name1",
        "drink": "drink1"
    }
    res.end(JSON.stringify(response));
});

var port = process.env.PORT || 8080;
app.listen(port, function() {
    console.log('Node.js listening on port ' + port);
});

示例获取请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
    <script type="text/javascript">
    /*fetch('http://localhost:8080/kfc')
                .then((res) => {
                    res.json().then((data) => {
                        console.log(data);
                    });
                })
                .catch((err) => {
                    console.log(err);
                });*/
    $.ajax({
        type: 'GET',
        url: 'http://localhost:8080/kfc',
        dataType: 'json',
        success: function(data) {
            console.log(data)
        }
    });
    </script>
</body>
</html>

【讨论】:

  • 我在某处读到使用dataType: 'jsonp' 作为从另一个端口访问的解决方案。使用您的解决方案,我得到了ReferenceError: cors is not defined,所以我包含了var cors=require('cors');,但我仍然遇到这些错误。
  • @RahulChawla 你能提供所有的api代码吗?例如在 pastebin 上
  • 这是我唯一的 api 代码。我在 localhost:3000/api/kfc 上提供 json 数据,localhost:8887/kfc.html @Mikhail 正在访问此 json 数据
  • 我应该把app.use(function(req, res, next) {...});放在哪里?里面router.get('/kfc', function(req, res, next) {...});
  • @RahulChawla 你有var app = express(); 变量吗?
猜你喜欢
  • 2017-11-08
  • 1970-01-01
  • 1970-01-01
  • 2017-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-09
相关资源
最近更新 更多