node.js - 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 标头中的令牌,但由于某种原因,它仍然抛出错误,我希望在它失控之前解决它们。
解决方案
推荐阅读
- python - 在来自列表的 URL inl Python 末尾的循环中添加值并附加输出
- primefaces - Primefaces DataTable - 回流不适用于 iOS
- python - 如何在两条曲线之间插值以获得python中的数据映射
- mysql - dbeaver 图标丢失 Ubuntu 20.04
- c# - POST Json Web API C#
- cypress - 赛普拉斯如何存储输入数据并解析以进行验证
- python - OGB 数据集,我无法从“ogb.nodeproppred”导入“PygNodePropPredDataset”
- python - Vscode 使用 jedi + pyright 时两次显示函数文档字符串
- visual-studio-code - 如何配置 VS Code 扩展,以便启用或禁用它们。取决于打开的工作区?
- angular - Angular:如何在 Typescript 中访问 HTML 标签类