如何使用app.use('/ my / api',handlers);

时间:2018-06-23 21:43:04

标签: express

我有一个带有Express服务器的Node.js和一个电影搜索应用程序的React(创建React应用程序)。

当我尝试登录或注册时-我不断在此http://localhost:5000/signinhttp://localhost:5000/signup上找不到404。

我相信我已经正确设置了路由。

const express = require('express');
const passport = require('passport');
const { signin, signup, verifiEmail, resendVerification } = require('../controllers/authController');
const { resetPassword, verifyResetPassword, resetPasswordNew } = require('../controllers/resetPasswordController');
const passportService = require('../services/passport');

const requireAuth = passport.authenticate('jwt', { session: false });
const requireSignin = passport.authenticate('local', { session: false });

const router = express.Router();
  router.get('/test', (req, res) => res.json({ msg: 'Auth route works' }));
  router.post('/signup', signup);
  router.post('/signup/verify-email', verifiEmail);
  router.post('/resend-verify-code', resendVerification);
  router.post('/signin', requireSignin, signin);
  router.post('/reset-password', resetPassword);
  router.post('/reset-password/verify', verifyResetPassword);
  router.post('/reset-password/new', resetPasswordNew);

module.exports = router;

如果我在这里错了,请纠正我...

我相信问题是我不太清楚如何正确设置Express服务器?

require('dotenv').config();
const express = require('express');
const path = require('path');
// const http = require('http');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const mongoose = require('mongoose');
const cors = require('cors');
const compression = require('compression');

const authRoutes = require('./routes/auth');

// Express app init
const app = express();
// const server = http.createServer(app); // added

// Connect MongoDB
mongoose.connect(process.env.MONGODB_URI);
mongoose.set('debug', true);

// const server = http.createServer(app); // custom location

// middleware
app.use(cors());
app.use(compression());
app.use(morgan('combined'));
app.use(bodyParser.json({ type: '*/*' })); // Send JSON responses
app.use(bodyParser.urlencoded({ extended: false })); // Parses urlencoded bodies

// router(app); // default

// Use Routes
app.use('/api/auth', authRoutes);

app.use(express.static(path.join(__dirname, 'build')));
app.get('/*', (req, res) => {
  res.sendFile(path.join(__dirname, 'build', index.html));
});

const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server running on port ${port}`));

如果我取消注释上面的router(app)并为配置不同的路由(没有Router)添加require语句,则该应用程序可以工作。

我想使用app.use('/my/router', handlers);的{​​{1}} INSTEAD,但似乎无法正常工作?

1 个答案:

答案 0 :(得分:0)

如果您的身份验证路由是通过以下方式定义的:

app.use('/api/auth', authRoutes);

然后,您将使用的网址是:

/api/auth/signup
/api/auth/signin

如果像您的问题一样,您希望/signup/signin工作,那么您需要将路线注册更改为:

app.use(authRoutes);

因此,前面没有添加的路径前缀。

要么更改您使用的URL,要么更改路由定义以匹配您要使用的URL。两者只需匹配即可。