【发布时间】:2016-07-06 20:06:48
【问题描述】:
我在 nodejs 上创建了一个极简 API,它以 JSON 格式返回数据。
但是每次我尝试进行 ajax#get 调用并将我的 API 作为 URL 传递时,我都会收到一个错误,并且从 Chrome 来看,我收到了一个 "Unexpected token :" 错误;
这里是 nodejs + express 中的服务器代码:
var
http = require( 'http' ),
express = require( 'express' ),
app = express(),
server = http.createServer( app );
app.get( '/', function( req, res ) {
console.log( 'req received' );
res.setHeader('Content-Type', 'application/json');
res.end( JSON.stringify({
Name : "Tom",
Description : "Hello it's me!"
}) );
});
server.listen(3000, function() {
console.log( 'Listening on 3000' );
});
"/" 返回的 JSON 为:{"Name":"Tom","Description":"Hello it's me!"}。
这是我从客户端 js 打来的电话:
$.ajax({
url: findUrl,
type: 'get',
dataType: 'jsonp',
success: function ( data ) {
self.name( data.Name );
self.description( data.Description );
},
error: function( jqXHR, textStatus, errorThrown ) {
alert(errorThrown);
}
});
绘制错误时我得到:"jQuery111108398571682628244_1403193212453 was not called"
有人可以帮我吗?
我知道已经有人问过这个问题,但我还没有找到修复我的程序的解决方案。
【问题讨论】:
-
检查您的
dataType- $.ajax() -
@Andreas :我猜你指的是“jsonp”,我把它改成了“json”。我现在收到“XMLHttpRequest 无法加载 localhost:3000。请求的资源上没有 'Access-Control-Allow-Origin' 标头。因此不允许访问 Origin 'null'。”我该如何解决这个问题?
标签: javascript jquery json node.js