Node.js(Express)REST服务POST方法返回404

时间:2016-04-15 08:32:09

标签: node.js express

我正在努力解决一个问题,这就是我的帖子方法返回404错误的原因。问题是get方法工作正常,但POST没有运气:(。

这是服务器端。

以下是代码以及我如何使用它

taxiSnitch.js

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

var podatki = require('../node_modules/my_modules/module_taxi');

router.use(cors());

router.post('/addCab', function (req, res, next) {
  console.log("im in");
});

router.get('/getAllCabs', function(req, res, next){
    podatki.getAllCabs(function(cabs){
        res.json(cabs);
    });
});
module.exports = router;

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 my_taxi_module = require('./routes/taxiSnitch');

var app = express();
var path = require('path');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

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

app.use(my_taxi_module);

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});


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

// 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: {}
  });
});

var server = app.listen(3000, function () {

});

module.exports = app;

enter image description here 如果有任何想法我错了,请帮帮我:)。

enter image description here

1 个答案:

答案 0 :(得分:1)

您的请求不是POST,而是GET。这意味着您用于发送请求的代码出现问题,您应该将方法从GET更改为POST。