Express路由器不适用于发布请求

时间:2015-08-23 21:15:03

标签: javascript node.js post express mean-stack

我开始使用整个MEAN Stack的东西。我正在组建一个小型测试/初学者应用程序来学习基础知识。我目前正尝试使用不同路由的快速路由器。我在使路线正常工作时遇到了一些麻烦。

当我去localhost:8000 / api时它运行得很好。但是当我尝试访问localhost:8000/api/users时,它会返回404错误:(

这是我的代码

var express = require('express');
var app = express(); 
var bodyParser = require('body-parser'); 
var morgan = require('morgan'); 
var mongoose = require('mongoose'); 
var port = process.env.PORT || 8000; 
var User = require('./app/models/user');

mongoose.connect('mongodb://localhost:27017/ApiDataBase');

app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());

app.use(function(req, res, next) 
{
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET', 'POST');
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, \
22 Authorization');
  next();
});

app.use(morgan('dev'));

// testing if express runs

app.get('/', function(req, res) {
  res.send('Welcome to this awesome site!');
});

// creating new instance of the router

var apiRouter = express.Router();

apiRouter.use(function(req, res, next){

  console.log('Somebody came to vist');

  next();
});

// testing the router

apiRouter.get('/', function(req, res) {
  res.json({ message: 'WWWUUUUHHÚÚÚ Welcome!'});
});

// I'm not getting this part to work

apiRouter.route('/users')

  .post(function(req, res) {

    var user = new User();

    user.name = req.body.name;
    user.username = req.body.username;
    user.password = req.body.password;

    user.save(function(err) {
        if(err){

            if(err.code == 11000)
                return res.json({ success: false, message: 'Þessi notandi er þegar til'});
            else
                return res.send(err);
        }

            res.json({ message: 'Notandi stofanður'});
    });


})

app.use('/api', apiRouter);

app.listen(8000);
console.log('Magic happens on port' + port);

2 个答案:

答案 0 :(得分:2)

  

当我尝试访问localhost:8000 / api / users时,它返回404错误

您没有GETlocalhost:8000/api/users的路线,您有POST路线:

apiRouter.route('/users')

  .post(function(req, res) {

也就是说,当您向GET发送localhost:8000/api/users请求时,快递无法找到该路由,因为它不存在。您应该根据POST请求对其进行测试。

答案 1 :(得分:1)

您宣布两次端点' /',一次在app.get('/'...)中,再次在apiRouter.get('/'...

删除此块,它应该有效:

// testing the router
apiRouter.get('/', function(req, res) {
  res.json({ message: 'WWWUUUUHHÚÚÚ Welcome!'});
});