ajax - Node.js 和 Express;后404

标签 ajax node.js express

我无法让我的服务器使用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) 

最佳答案

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

关于ajax - Node.js 和 Express;后404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26516022/

相关文章:

node.js - 从 mongoose 集合中删除最新创建的文档

javascript - 检查 header 值是否匹配

javascript - 在 async.each 的帮助下在 foreach 中调用同步函数(带回调)

javascript - Sencha Touch - AJAX 不工作

node.js - 使用 nodeJS 将多个值推送到 mongodb 数组

javascript - AJAX 成功后无法设置数据 ID?

node.js - 您如何获得在 https 中使用的 key 和证书对?

mysql - 我什么时候应该使用 mongoDB 而不是关系数据库

java - 如何在ajax调用中获得超过1个响应

ajax - 使用 API 和 AJAX 发送/包含 'name' 字段到 Mailchimp