对不起,我不太明白秘密密钥在koa中是如何工作的.在koa中,对象keys
上有一个字段app
,将使用如下:
const app = new Koa();
app.keys = ['some secret', 'another secret', 'or more ...']; // it's an
// array right?
Run Code Online (Sandbox Code Playgroud)
然后,在使用koa-csrf
中间件时,默认情况下内置程序csrf.middleware
不使用提供的密钥app.keys
.如果我使用默认中间件,我需要创建另一个在会话上设置密钥的中间件.
app.use(session()); // koa-generic-session
app.use(async (ctx, next) => { // without this custom middleware
ctx.session.secret = 'yet another secret'; // POST /protected-route
await next(); // will give 403
}); // missing secret
csrf(app);
app.use(csrf.middleware);
Run Code Online (Sandbox Code Playgroud)
当我使用Flask时,我只需要提供一个由string
非设置的密钥array
.为什么需要多个密钥?只使用一个整个应用程序还不够?
我们为什么要做这个
router.get('/data', async (ctx, next) => {
ctx.body = dummyjson.parse(data);
await next();
});
router.get('/data/:x', async (ctx, next) => {
const newData = dataRepeat.replace('%(x)', ctx.params.x);
ctx.body = dummyjson.parse(newData);
await next();
});
Run Code Online (Sandbox Code Playgroud)
有什么用? await next()
没有它,它会工作得很好.yield next
在路由器的末尾添加了koa 1,预计会发生类似的事情.
我有两个实体,用户和员工.所以我想在不同的端点都使用CRUD,但是它们都将安装在"api"下,所以我可以定义api_v1,api_v2等等.端点将是这样的:
get api/users
put api/users/12
delete api/users/12
get api/employees
....
Run Code Online (Sandbox Code Playgroud)
我的两条路线都无法获得"api"前缀.无法使用koa-mount.
我的文件:
server.js
// Dependencies
import Koa from 'koa'
import mongoose from 'mongoose'
import logger from 'koa-logger'
// import parser from 'koa-bodyparser';
import convert from 'koa-convert'
import serve from 'koa-static'
import Router from 'koa-router'
import session from 'koa-generic-session'
import mount from 'koa-mount'
// A seperate file with my routes.
import routingUsers from './users'
import routingEmployees from './employees'
// config
const config = require("./config/config")
// connect to the database
mongoose.connect(config.mongo.url)
mongoose.connection.on('error', …
Run Code Online (Sandbox Code Playgroud) 我有一个 Koa 2 应用程序,并且 /signup 的帖子由此函数处理:
import User from 'models/user';
export const signup = async (ctx, next) => {
const { email, password } = ctx.request.body;
try {
const existingUser = await User.findOne({ email });
if (existingUser) {
ctx.body = { error: 'Email is in use' };
return next();
}
const user = new User({
email,
password,
});
await user.save();
ctx.body = { success: true };
} catch (e) {
next(e);
}
return next();
};
Run Code Online (Sandbox Code Playgroud)
该函数接收到正确的数据,但await User.findOne().exec();
永远不会返回并卡住。
我认为问题出在那里,因为如果我删除,代码会正常执行。如果我切换到 …
我有一个控制器来查找一个角色,然后用它做一些事情,控制器看起来像:
router.post('/profile/characters', async ctx => {
try {
ctx.type = 'json';
let req = ctx.request;
if (!('charname' in req.body) || !('charserver' in req.body)) {
return res.json({
'success': false,
error: 'You are missing either the character name, or server'
});
}
let foundChar = await new Promise((res, rej) => {
bnet.wow.character.aggregate({
origin: 'us',
realm: req.body.charserver,
name: req.body.charname,
fields: ['items', 'talents']
}, (err, charData) => {
if (err) {
console.log(err);
return rej(err);
}
return res(charData);
});
});
if ('status' in foundChar) { …
Run Code Online (Sandbox Code Playgroud) 我想在Typescript中使用Facebook的DataLoader和Koa2.我希望每个请求的DataLoader实例与我的每个请求数据库连接一起使用.如何最好地实现这一目标?
我目前的方法是增加Koa2上下文,但我失败了,因为我不知道如何修复类型定义.
这是我对模块增强的尝试......
import 'koa';
declare module 'koa' {
namespace Application {
interface BaseContext {
dataLoader(): any;
}
}
}
Application.BaseContext.prototype.dataLoader = function() {
console.log("Cannot find name 'Application' at line 11 col 1");
}
Run Code Online (Sandbox Code Playgroud)
除了日志调用中显示的错误之外,我还会Property 'dataLoader' does not exist on type 'BaseContext'
在导入上述内容并尝试调用时获取dataLoader
.
干杯
有人使用 koa.js 和流吗?
考虑这个例子
const fs = require('fs');
const Koa = require('koa');
const app = new Koa();
app.use(async (ctx) => {
ctx.body = fs.createReadStream('really-large-file');
});
app.listen(4000);
Run Code Online (Sandbox Code Playgroud)
如果用户中止请求我得到
Error: read ECONNRESET
at _errnoException (util.js:1024:11)
at TCP.onread (net.js:618:25)
Run Code Online (Sandbox Code Playgroud)
或者
Error: write EPIPE
at _errnoException (util.js:1024:11)
at WriteWrap.afterWrite [as oncomplete] (net.js:870:14)
Run Code Online (Sandbox Code Playgroud)
处理此类错误的正确方法是什么?
PS请求中止后我没有错误
const fs = require('fs');
const express = require('express');
const app = express();
app.get('/', (req, res) => {
fs.createReadStream('really-large-file').pipe(res);
});
app.listen(4000);
Run Code Online (Sandbox Code Playgroud)
我试过的PPS
app.use(async (ctx) => {
fs.createReadStream('really-large-file').pipe(ctx.res);
ctx.respond = …
Run Code Online (Sandbox Code Playgroud) 我一直在尝试使用 internetross's March 2018 的答案,但无济于事。我也使用 Jest、Supertest,就我而言,还使用 Koa 和 Passport。
在 Visual Studio 中使用 REST 客户端,没问题。会话通过,Passport 进行身份验证,然后我获取数据。但在玩笑中,不行。我可以正常登录,我得到 Koa:sess 正常,但我无法发出经过身份验证的请求。
有人看到下面的内容吗?
const supertest = require('supertest')
const app = require('../app.js')
const http = require('http')
const agent = supertest.agent((http.createServer(app.callback())))
let session = null
beforeAll(async () => {
const response = await agent
.post('/v1/users/login')
.set({'content-Type': 'application/json'})
.send({ username: 'username', password: 'password' })
session = response.headers['set-cookie'][0]
.split(',')
.map(item => item.split(';')[0])
.join('; ')
console.log(stringify(session))
expect(response.status).toEqual(200)
})
describe('user tests', () => {
test('data', async () => { …
Run Code Online (Sandbox Code Playgroud) 如何在nodejs中对多个函数进行分组和导出?
我试图在 utils.js 中对我所有的 util 函数进行分组:
async function example1 () {
return 'example 1'
}
async function example2 () {
return 'example 2'
}
module.exports = { example1, example2 }
Run Code Online (Sandbox Code Playgroud)
然后在 home.js 中导入:
import { example1, example2 } from '../utils'
router.get('/', async(ctx, next) => {
console.log(example1()) // Promise { 'example 1' }
})
Run Code Online (Sandbox Code Playgroud)
我以为我会得到'example 1'
上面的测试用例?
有任何想法吗?
使用Koa2,我不确定如何将数据写入响应流,因此在Express中,它类似于:
res.write('some string');
Run Code Online (Sandbox Code Playgroud)
我知道我可以将流分配给它,ctx.body
但是我对node.js流太不熟悉,所以不知道如何创建该流。
koa2 ×10
koa ×5
node.js ×5
javascript ×4
koa-router ×2
async-await ×1
babeljs ×1
ecmascript-6 ×1
express ×1
jestjs ×1
koa-session ×1
mongoose ×1
secret-key ×1
stream ×1
streaming ×1
supertest ×1
typescript ×1