向节点发送ajax get请求,响应未定义

时间:2015-12-29 09:34:17

标签: javascript jquery ajax node.js get

我有一个运行单个网页的Node服务器。该页面有一个联系表格,带有一个发送按钮。

如果我点击发送,将运行以下代码:

$('.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,而是发送字符串,则消息就像

Uncaught ReferenceError: test is not defined

2 个答案:

答案 0 :(得分:3)

客户端期待jsonp,但是你发送了json。

试试这个:

router.get('/', function(req, res, next) {
    res.jsonp({test:'test'});
});

答案 1 :(得分:1)

如果您不需要克服跨域限制,则可以使用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"
    // ...
相关问题