无法通过 HTTP req/res 使用 Express.js 完成登录/注册路由器

问题描述 投票:0回答:1

因此,我尝试通过中间件功能和通过 HTTP 请求/响应的 POST 方法为用户设置登录/注册路由器,但我在完成两者的路由器时遇到困难。我在登录路由中创建了“200”和“401”状态代码,但只是想弄清楚如何为注册用户路由器执行此操作。

这是在 VS Code 上的 Express.js 中编码的。 PS 我在 3060 上侦听端口,当我输入 localhost:3060 时,我在 Chrome 浏览器上收到 Cannot Get 404 错误代码。我的 app.js 模块中没有任何特定的语法错误。

我什至尝试阅读express.com和MDN上的文档,但没有找到任何解决方案。我知道这不会那么困难,因为最终我想实现注销路由并且 电子邮件 最终使用正则表达式和哈希密码。但无论如何,这里是 app.js 和 package.json 的代码

const express = require('express');
const app = express();

const port = 3060;

app.use('/login',loginUser);

//Router for user registering an account with middleware
app.post('/register', (req, res, next) => {

});

// Router (API) for login in Express.js using HTTP Req & Res (POST)
app.post('/login', (req, res, next) => {

    if (email) {
        // Successful response (200) code
        res.status(200);
    } else {
        // Error status (401) code
        res.status(401), {
            error: 'invalid email',
        }
    }

    if (password) {
        res.status(200);
    } else {
        res.status(401), {
            error: 'Invalid password',
        }
    }

    res.send('Successful login');
    console.log(res.locals.loggedIn)

    const loggedIn = {
        email: '[email protected]',
        password: 'Password!123', 
    };
});

function loginUser(req, res, next){
    //retrieve info from req object
    res.locals.loggedIn = true
    console.log("Successful login!")
    next();
}

app.listen(port, () => {
    console.log(`Listening on port ${port}..`);
})

我尝试检查 app.js 的代码,据我所知,没有语法问题。我不确定我是否在浏览器上收到此错误代码,因为我对两个路由器都使用 POST。

node.js authentication http-post httprequest httpresponse
1个回答
0
投票

您没有设置路线

app.get('/')
app.get('/login')
,这就是为什么您在访问
404
时会收到
localhost:3060
错误。

© www.soinside.com 2019 - 2024. All rights reserved.