发送ajax获取请求到节点,响应是未定义的
我有一个运行单个网页的节点服务器。 该页面有一个联系表单和一个发送button。
如果我点击发送,下面的代码将运行:
$('.contactsend').click(function(){ $.ajax({ method: "GET", url: "http://127.0.0.1:3000/contact", dataType: "jsonp" }) .done(function(data) { alert( data ); }) .fail(function() { alert( "error" ); }) .always(function() { alert( "complete" ); }); })
到目前为止,这似乎确定,页面已达到。
这就是中间件所做的事情:
router.get('/', function(req, res, next) { res.send({test:'test'}) //res.send('test') });
发送完毕后,网页显示如下信息:
Uncaught SyntaxError: Unexpected token :
如果我不发送json
,而是string,消息就像
Uncaught ReferenceError: test is not defined
客户端期待jsonp,但你正在发送json。
尝试这个:
router.get('/', function(req, res, next) { res.jsonp({test:'test'}); });
如果您不需要克服跨域限制,则可以使用res.json()
。 尝试:
router.get('/', function(req, res, next) { res.json({test:'test'}); });
并将ajax.dataType
更改为json
:
$.ajax({ method: "GET", url: "http://127.0.0.1:3000/contact", dataType: "json" // ...