Express.js-如果路由有多个错误-404错误

时间:2018-06-22 13:03:54

标签: express

GET / user / me-发送回404(找不到资源)

如果我将第二个'/'更改为'_'(即GET users_me),那么它将起作用。

我有两个问题:

1)如何修复它,以便可以使用“ GET / user / me”?

2)它可以与下划线一起使用,因此使用斜杠与下划线是否有任何优势?

////////////代码

require('./config/config');

const _ = require('lodash');
const express = require('express');
const bodyParser = require('body-parser');
const {ObjectID} = require('mongodb');

//const multer = require('multer');
//const router = express.Router();
var renameKeys = require('rename-keys');

var {mongoose} = require('./db/mongoose');

//var {Todo} = require('./models/todo');
var {User} = require('./models/user');
var {authenticate} = require('./middleware/authenticate');

var app = express();
const port = process.env.PORT;

app.use(bodyParser.json());




// GET users/me

app.get('/users_me', authenticate, (req, res) => {
  res.send(req.user);
});



// POST /users -- signing up a new user [how will this handle logging in instead of signing up?]
app.post('/users', (req, res) => {
  var body = _.pick(req.body, ['email', 'password']);
  var user = new User(body);
  user.save().then(() => {
    return user.generateAuthToken();
  }).then((token) => {
    res.header('x-auth', token).send(user);
  }).catch((e) => {
    res.status(400).send(e);
  })
});



app.listen(port, () => {
  console.log(`Started up at port ${port}`);
});

module.exports = {app};

1 个答案:

答案 0 :(得分:0)

第一个问题:

只是改变

app.get('/users_me', authenticate, (req, res) => {
  res.send(req.user);
});

app.get('/users/:me', authenticate, (req, res) => {
  res.send(req.user);
});

然后发出Get请求:

somehost:someport/users/myusername

第二个问题:

路由就像文件系统一样工作:

/path/subpath/

因此,您不能使用下划线替换斜杠“ /”

信息:您可以在GET请求的URL中传递用户的ID或名称(取决于您的逻辑):

GET请求(在本例中为端口3000的localhost):

localhost:3000/users/getuserbyid/20

路线:

 router.get('/getuserbyid/:id', ..... 

希望有帮助;)