【发布时间】: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