【问题标题】:Node.js and Express; POST 404Node.js 和 Express;发布 404
【发布时间】:2014-10-23 04:17:13
【问题描述】:

我无法让我的服务器使用 node.js 和 express 从客户端调用函数。我不需要传递数据,我只需要提醒服务器它应该调用一个函数。这就是我所拥有的(在遵循大量教程之后):

客户:

$.ajax({
        type: 'POST',
        url: 'http://localhost:3001/admin',
        sucess: function() {
            console.log('sucess');
        }

服务器:

var express = require('express');
var app = express();
var server = require('http').Server(app);

app.set('port', process.env.PORT || 3001);

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hjs');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

app.post('/admin', function(req, res) {
  console.log("admin refresh");
  res.send(200);
});

错误:

POST http://localhost:3001/admin 404 (Not Found) 

【问题讨论】:

  • url: '/admin' - 删除 localhost:3001
  • @tymeJV 仍然获得 404
  • typo: sucess -> 成功(不是您的明确问题,而是浏览器 jquery 中的错误)

标签: ajax node.js express


【解决方案1】:

您的中间件顺序错误。快报按顺序处理它们。将 app.post('/admin... 行移到 Not Found 中间件上方。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-13
    • 2018-10-08
    • 2013-09-28
    • 1970-01-01
    • 2016-07-06
    相关资源
    最近更新 更多