简体   繁体   English

基本路由上的NodeJS + Express 404

[英]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! 我已经早些时候创建了一个Node / Express教程应用程序,并且运行良好,并且在尝试将其复制并创建新项目(ubuntu,然后是Windows)后,基本路由每次都失败并出现404,这非常令人沮丧!

I'm trying to reach /finddrink/margarita or whatever drink I want. 我正在尝试达到/finddrink/margarita或我想要的任何饮料。

Here's my app.js with the relevant stuff: 这是我的app.js及其相关内容:

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: 这是我的index.js,位于路由文件夹中:

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: 最后,该函数尝试访问此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: 您的路线在index.js文件中设置为findrink:

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

But you are asking for finddrink with double d. 但您要的是带有双d的finddrink。

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: 这样,您就可以将API扩展到更多路由:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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