简体   繁体   中英

NodeJS + Express 404 on basic routing

I already created a tutorial Node/Express app earlier and it worked fine, and after trying to copy it and make my new project (ubuntu, then windows), basic routing fails and 404s every time, super frustrating!

I'm trying to reach /finddrink/margarita or whatever drink I want.

Here's my app.js with the relevant stuff:

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

var app = express();

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

And here is my index.js, in the routes folder:

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

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

/*GET drink recipe*/
router.get('/findrink/:name', function (req,res){
    var db = req.db;
    var drinkName = req.params.name;
    db.collection('recipes').findOne({name: drinkName}, function (err, result) {
        res.send(result);
    });
});
module.exports = router;

And lastly, the function trying to access this GET:

function loadDrink(drinkToGet) {
  var address = '/finddrink/' + drinkToGet;

  $.getJSON(address, function (item) {
    document.getElementById('drinkTitle').innerHTML = item.name;
  });
};

I'm reading the code on my laptop with the running project, then on my desktop with almost identical code, and can't seem to find anything wrong, any ideas? Thanks!

You have a typo:

Your route is setup as findrink in the index.js file:

router.get('/findrink/:name', function (req,res){
});

But you are asking for finddrink with double d.

You should consider renaming you routes to a more restful approach:

router.get('/drinks/:name', function (req,res){
});

or

router.get('/drinks/find/:name', function (req,res){
});

This way you can then extend your API to more routes:

// POST /drinks/ creates new drink
router.post('/drinks/', function (req,res){
});

// PUT /drinks/:name edits a drink by na,e
router.put('/drinks/:name', function (req,res){
});

// DELETE /drinks/:name deletes a drink by name
router.delete('/drinks/:name', function (req,res){
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM