Skip to content

Instantly share code, notes, and snippets.

@ryanlid
Created August 13, 2019 01:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanlid/4a311cea4ea76fe5ecc8fb13a10a3b23 to your computer and use it in GitHub Desktop.
Save ryanlid/4a311cea4ea76fe5ecc8fb13a10a3b23 to your computer and use it in GitHub Desktop.
使用 koa-bodyparser 中间件解析POST请求参数
const koa = require("koa");
const app = new koa();
const bodyParser = require("koa-bodyparser");
app.use(bodyParser());
app.use(async ctx => {
if (ctx.url === "/" && ctx.method === "GET") {
ctx.type = "html";
let html = `
<h1>登录</h1>
<form action="/" method="post">
<p>用户名</p>
<input type="text" name="username" /><br>
<p>密码</p>
<input type="text" name="password" /><br>
<button type="submit">submit</button>
</form>
`;
ctx.body = html;
} else if (ctx.url === "/" && ctx.method === "POST") {
let postData = ctx.request.body;
ctx.body = postData;
}
});
app.listen(3000, () => {
console.log("server is running at http://localhost:3000");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment