无法 POST /login - POST http://localhost:3000/login 404(未找到)
Posted
技术标签:
【中文标题】无法 POST /login - POST http://localhost:3000/login 404(未找到)【英文标题】:Cannot POST /login - POST http://localhost:3000/login 404 (Not Found) 【发布时间】:2021-10-14 21:56:12 【问题描述】:我正在提供我的登录表单,但由于某种原因无法发布登录并实际登录。我认为这与我的路由文件夹有关,但我已经尝试了几次路由迭代并且可以' t 似乎弄明白了。我不断收到错误 POST http://localhost:3000/login 404 (Not Found)。
我的应用在 3000 端口上运行。
CRUD 路径:“Routes”文件夹->artist.js
const express = require('express');
const router = express.Router();
const passport = require('passport');
const Artist = require('../models/artist');
const catchAsync = require('../utils/catchAsync');
const ExpressError = require('../utils/ExpressError');
/* lists artists from database */
router.get('/', async (req, res) =>
const artists = await Artist.find();
res.render('artists/index', artists )
);
router.get('/new', (req, res) =>
res.render('artists/new');
);
router.get('/login', (req, res) =>
res.render('artists/login');
)
/* shows specific artists that exist in database */
/* link - show.ejs */
router.get('/:id', catchAsync(async(req, res,) =>
const artist = await Artist.findById(req.params.id);
if (!artist)
req.flash('error', 'Cannot find that Artist');
return res.redirect('/artists');
res.render('artists/show', artist );
));
/* artist edits form*/
router.get('/:id/edit', catchAsync(async (req, res) =>
const artist = await Artist.findById(req.params.id);
if (!artist)
req.flash('error', 'Cannot find that Artist');
return res.redirect('/artists');
res.render('artists/edit', artist );
))
router.put('/:id', catchAsync(async (req, res) =>
const id = req.params;
const artist = await Artist.findByIdAndUpdate(id, ...req.body.artist );
res.redirect(`/artists/$artist._id`);
))
/* creating a new artist */
router.post('/new', catchAsync(async(req, res) =>
try
const email, username, password, location, genre, about, size = req.body;
const artist = new Artist( email, username, location, genre, about, size );
const registeredArtist = await Artist.register(artist, password);
req.flash('success', 'Successfully signed up!');
res.redirect(`/artists/$artist._id`)
catch (e)
req.flash('error', 'Sorry, an artist with that email already exists');
res.redirect('/artists');
));
/** Where I'm encountering my error **/
router.post('/login', passport.authenticate('local', failureFlash: true, failureRedirect: '/login' ), (req, res) =>
req.flash('success', 'Welcome back!');
res.redirect('/artists');
)
/* delete a post */
router.delete('/:id', catchAsync(async (req, res) =>
const id = req.params;
await Artist.findByIdAndDelete(id);
res.redirect('/artists');
))
router.all('*', (req, res, next) =>
next(new ExpressError('Page Not Found', 404))
)
router.use((err, req, res, next) =>
const statusCode = 500, message = 'Something went wrong' = err;
res.status(statusCode).render('error');
)
module.exports = router;
这是带有路径的 ejs 表单:“Views”文件夹->“艺术家”文件夹-> login.ejs
<% layout('layouts/boilerplate')%>
<div class="container d-flex justify-content-center align-items-center mt-5">
<div class="row">
<div class="col-md-6 offset-md-3 col-xl-4 offset-xl-4">
<div class="card shadow">
<img src="https://images.unsplash.com/photo-1571863533956-01c88e79957e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1267&q=80"
class="card-img-top" />
<div class="card-body">
<h5 class="card-title">Login</h5>
<form action="/login" method="POST" class="validated-form" novalidate>
<div class="mb-3">
<label class="form-label" for="artist[username]">Username</label>
<input class="form-control" type="text" id="artist[username]" name="artist[username]" required autofocus>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="mb-3">
<label class="form-label" for="artist[password]">Password</label>
<input class="form-control" type="password" id="artist[password]" name="artist[password]" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<button class="btn btn-success btn-block">Login</button>
</form>
</div>
</div>
</div>
</div>
</div>
下面是我的 app.js 来显示所有路线。我也有“用户”和“事件”。只有用户和艺术家可以登录。
const express = require('express');
const path = require('path');
const mongoose = require('mongoose');
const ejsMate = require('ejs-mate');
const catchAsync = require('./utils/catchAsync');
const methodOverride = require('method-override');
const passport = require('passport');
const LocalStrategy = require('passport-local');
const session = require('express-session');
const Artist = require('./models/artist');
const Event = require('./models/event');
const User = require('./models/user');
const flash = require('connect-flash');
const eventRoutes = require('./routes/events');
const userRoutes = require('./routes/users');
const artistRoutes = require('./routes/artists');
const dbUrl = process.env.DB_URL || 'mongodb://localhost:27017/macro-tickets';
mongoose.connect(dbUrl,
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false
);
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", () =>
console.log("Database connected");
);
const app = express();
app.engine('ejs', ejsMate);
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'))
/* method override allows to serve put requests into the database */
app.use(express.urlencoded( extended: true ));
app.use(methodOverride('_method'));
app.use(express.static(path.join(__dirname, 'public')))
const sessionConfig =
secret: 'thisshouldbeabettersecret!',
resave: false,
saveUninitialized: true,
cookie:
httpOnly: true,
expires: Date.now() + 1000 * 60 * 60 * 24 * 7,
maxAge: 1000 * 60 * 60 * 24 * 7
app.use(session(sessionConfig))
app.use(flash());
app.use((req, res, next) =>
res.locals.success = req.flash('success');
res.locals.error = req.flash('error');
next();
)
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.use(new LocalStrategy(Artist.authenticate()));
passport.serializeUser(User.serializeUser());
passport.serializeUser(Artist.serializeUser());
passport.deserializeUser(User.deserializeUser());
passport.deserializeUser(Artist.deserializeUser());
app.use('/events', eventRoutes)
app.use('/users', userRoutes);
app.use('/artists', artistRoutes)
app.listen(3000, () =>
console.log('Serving on port 3000')
)
表单正在 POST 到“/login”,但没有通过。任何想法我做错了什么?
【问题讨论】:
【参考方案1】:如果要使用此路由器,您正在调用它
app.use("/your-route", require("../routes/artists.js")
正确的地址是http://localhost:3000/your-route/login
。
在你的情况下,我似乎能想到你在做什么:
app.use("/artists", require("../routes/artists.js")
那么发布请求将是http://localhost:3000/artists/login
。
【讨论】:
感谢 Jorge 是有道理的——但是,当我更新到 router.post('/artists/login', passport.authenticate..) 的路由时,服务器仍然为我提供 localhost:3000/login。任何想法为什么我更新的 POST 无法正常通过? 如果我将 ejs 页面发布位置修改为“/artists/login”,这是我得到的错误:login:1 POST localhost:3000/artists/artists/login404 (Not Found) 我可以正确假设您没有使用路径文件之外的任何其他 get 方法吗?您可以更新问题并显示您的快递文件吗? @econobro 我在另外两条路线上收到了请求 - 1) 事件和 2) 用户。类似的格式,但添加了 app.js 以获得额外的上下文。谢谢豪尔赫!【参考方案2】:你可以试试这个, 在你的 app.js 文件中更新它
app.use(require('./routes/artists'))
那么您的请求链接将类似于 http://localhost:3000/login
【讨论】:
感谢@dlyaswanth 的回复。试过了,但我得到了客户端闪存“缺少凭据”,我在任何地方都没有作为回报,所以我猜它是预建的闪存响应之一。在上面添加了我的 app.js 作为上下文。 嗨@dlyaswanth - 添加在上面。以上是关于无法 POST /login - POST http://localhost:3000/login 404(未找到)的主要内容,如果未能解决你的问题,请参考以下文章