首页 > 解决方案 > Fetch API 在身份验证期间无法获取,同时出现 CORS 错误

问题描述

我有一个按钮,可以向我的使用 KOA 和 JWT 的 API 进行获取。单击时启动的获取的 javascript 是:

<script>

        function loginButton(user, pass) {
            fetch('http://localhost:5454/api/login', {
                method: "post",
                headers: {
                    'Content-Type': "application/json"
                },
                body: JSON.stringify({
                    username: user,
                    password: pass
                })
            })
            .then( (response) => {
                console.log("Success")
            })
            .catch(e => console.log(e));
        }

    </script>

我的身份验证代码是:

router.post(`${BASE_URL}/login`, async (ctx) => {
const reqUsername = ctx.request.body.username
const reqPassword = ctx.request.body.password

const unauthorized = (ctx) => {
    ctx.status = 401
    ctx.body = {
        error: 'Invalid username or password'
    }
}

let attemptingUser
try {
    attemptingUser = await Employee.findOne({ where: { username: reqUsername }})
    if (attemptingUser != null && attemptingUser.password === reqPassword) {
        ctx.status = 200
        ctx.body = {
            username: attemptingUser.username,
            given_name: attemptingUser.given_name,
            role: attemptingUser.role,
            created_at: attemptingUser.createdAt,
            updated_at: attemptingUser.updatedAt,
        }

        const token = jwt.sign({ username: attemptingUser.username, role: attemptingUser.role }, SECRET)
        ctx.set("X-Auth", token)
    } else {
        unauthorized(ctx)
    }

} catch(err) {
    console.error(err)
    console.error(`Failed to find username: ${reqUsername}`)
    unauthorized(ctx)
}

})

我的 KOA 启动代码是:

    require('dotenv').config()
const Koa = require('koa')
const Router = require('koa-router')
const bodyParser = require('koa-bodyparser')
const baseRoutes = require('./routes')
const cors = require('@koa/cors');

const PORT = process.env.PORT || 8080

const app = new Koa()


app.use(bodyParser())
app.use(baseRoutes.routes())
app.use(cors());

app.listen(PORT, () => {
    console.log(`Server listening on ${PORT}`)
})

我为我的 http 服务器使用端口 8080,为我的 npm 服务器使用端口 5454。我在 Fetch 的捕获中收到 Failed to Fetch,以及与响应标头中没有 Access-Control-Allow-Origin 标头相关的 CORS 错误。我已经尝试了几件事,并准备用新的眼光来看待它,有什么建议吗?

编辑:我成功地接收了 X-Auth 标头中的令牌,但由于某种原因,它仍然抛出错误,我希望在它失控之前解决它们。

标签: node.jsnpmcorsjwtkoa

解决方案


推荐阅读