简体   繁体   English

使用JQuery进行Express和ajax发布

[英]Express and ajax posting using JQuery

Express doesn't seem to be responding to my ajax request. Express似乎没有响应我的ajax请求。 The post request status appears to be pending for a long time when I look at it in the network tab of the chrome inspector and then fails. 当我在chrome检查器的网络选项卡中查看并且失败时,帖子请求状态似乎很长时间未决。 This is my express code: 这是我的快递代码:

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.cookieParser());
  app.use(express.session({secret: 'fasfasasasfasfa'}));
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(express.session());
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});

app.post('/test.html', function (req,res) {
  console.log(req.body);
  res.send({ some: JSON.stringify({response:'json' })});
  res.end();
})

And here's my jQuery code: 这是我的jQuery代码:

working = function() {
    console.log("works")
}

$.ajax({
    url:"test.html",
    data: {'name':'hello'},
    type: "POST",
    success: working
  })    

The success function never gets called, and the console log of req.body doesn't seem to work either. 永远不会调用成功函数,并且req.body的控制台日志似乎也不起作用。

Thanks for the help! 谢谢您的帮助!

As you mentioned in the comments, you're getting a status code of 0 back. 正如您在评论中提到的那样,您的状态代码为0。

Does an HTTP Status code of 0 have any meaning? HTTP状态代码0是否有任何意义?

Check to make sure you're server is reachable from where you're testing and that the URL your making the request to is actually pointing at the server you want to send the request to. 检查以确保您可以从您正在测试的位置访问服务器,并且您发出请求的URL实际上指向您要将请求发送到的服务器。

In other words you probably need to fix this line 换句话说,您可能需要修复此行

url:"test.html",

You can't use the .html extension on a route in Express as this makes it think its looking for a static resource. 您不能在Express中的路由上使用.html扩展名,因为这会让它认为它正在寻找静态资源。 Use "pretty URLs" instead. 请改用“漂亮网址”。

// Express code...
app.post('test', function(req, res, next){
  // Do stuff to process POST request
});

// AJAX code...
$.ajax({
  url: 'test',
  ...
});

Hope that helps! 希望有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM