最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Express router not working for post requests - Stack Overflow

programmeradmin1浏览0评论

I'm getting started with the whole MEAN Stack thing. I'm putting together a small test / beginners app to learn the basics. I'm currently trying to the express router for different routes. I'm having some trouble getting the routes working correctly.

When I go to localhost:8000/api it works just fine. But when I try to access localhost:8000/api/users it returns a 404 error :(

Here's my code

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('Wele 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ÚÚÚ Wele!'});
});

// 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);

I'm getting started with the whole MEAN Stack thing. I'm putting together a small test / beginners app to learn the basics. I'm currently trying to the express router for different routes. I'm having some trouble getting the routes working correctly.

When I go to localhost:8000/api it works just fine. But when I try to access localhost:8000/api/users it returns a 404 error :(

Here's my code

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('Wele 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ÚÚÚ Wele!'});
});

// 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);
Share Improve this question edited Aug 11, 2017 at 15:43 Cœur 38.8k25 gold badges205 silver badges277 bronze badges asked Aug 23, 2015 at 21:15 SteinarSteinar 4512 gold badges7 silver badges10 bronze badges 2
  • I noticed that you use post method for '/users'. Therefore, it will never return html page on browser. – Haoyu Chen Commented Aug 23, 2015 at 21:36
  • As far as I understood, he wants to use POST, not GET, in /api/users because he's saving the User in mongoose within the block :) – MaC Commented Aug 23, 2015 at 21:39
Add a ment  | 

3 Answers 3

Reset to default 4

when I try to access localhost:8000/api/users it returns a 404 error

You don't have a GET route to localhost:8000/api/users, you have a POST route to it:

apiRouter.route('/users')

  .post(function(req, res) {

That said, when you send a GET request to localhost:8000/api/users, express can't find the route, because you it doesn't exist. You should test it against a POST request.

You are declaring twice the endpoint '/', once in your app.get('/'...) and once more in apiRouter.get('/'...

Delete this block and it should work:

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

its reason may be the installation error ,Just re-install the express-grnerator.

You can Install it by using the following mand on terminal .

• npx install express-generator --hbs

--hbs means view engine handlebar

发布评论

评论列表(0)

  1. 暂无评论