在Webstorm node express app:router.post()显示错误:未解析的函数或方法post()

时间:2016-02-24 10:12:50

标签: javascript node.js express webstorm

当我运行localhost:3000 / users / yu时,我找不到404。为什么post()出现未定义?当我从我的iOS应用程序运行POST时,我收到“未定义的令牌”错误。我正在运行节点v5.7.0并表达v4.13.4项目是使用express-generator生成的,用于创建Webstorm项目。

    var express = require('express');
    var router = express.Router();

        var express = require('express');
    var router = express.Router();


    /* GET users listing. */
    router.get('/', function(req, res) {
      res.send("yoma");
    });

    router.post('/yu', function(req, res) {
      var test = req.body;
      //parse test
    });

我的app.js看起来像这样:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

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

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

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

// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;

1 个答案:

答案 0 :(得分:1)

当您将浏览器导航至localhost:3000/users/yu时,它会GET进行http查询,但在您的路由器中,POST只有'/yu'处理程序

router.post('/yu', function(req, res) {
      console.log(req.body);
});

'/yu'添加GET处理程序,例如

router.get('/yu', function(req, res) {
      console.log(req.body);
});

之后,导航到localhost:3000/users/yu

时不会出现404错误