最近在用 get 传参的时候遇到一个问题,不想用 form 提交参数的时候( form 传参会在url后面生成 ?a=1 这种小尾巴),怎么在 get 请求中传参?
cookie 传参
调用js,把需要传给下一个路由的值存为 cookie ,再在下一个路由进行获取。(若需要传递多个参数,建议还是用 form 进行传参。实在不想用 form 也可以,将多个参数存为一个 cookie 字符串就好了,获取的时候再拆开)
好了,直接上 demo 吧。
demo
const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
const bodyParser = require('koa-bodyparser');app.use(bodyParser());
app.use(router.routes());router.get('/',async ctx => {ctx.body = `<div><label>邮箱:</label><input type="email" id="email" placeholder="请输入邮箱"></div><div><label>密码:</label><input type="password" placeholder="密码"></div><input type="button" name="" value="登录" onclick="set()"><script>function set() {var cvalue = document.getElementById('email').value; //获取输入的 emaildocument.cookie = cvalue; //直接将输入的 email 设置为cookiewindow.location.href='/welcome' //页面跳转
}
</script>`
});router.get('/welcome',async ctx => {let cookie = ctx.request.header.cookie; //从get请求头中获取cookiectx.body = `<h1>welcome</h1><p>${cookie}</p>`});app.listen(3000)
下面再给一个传统的 form 传参的 demo
const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
const bodyParser = require('koa-bodyparser');app.use(bodyParser());
app.use(router.routes());router.get('/',async ctx => {ctx.body = `<form action="/welcome" method="get"><div><label>用户名:</label><input type="text" name="name" placeholder="请输入用户名"></div><div><label>邮箱:</label><input type="email" name="email" placeholder="请输入邮箱"></div><div><label>密码:</label><input type="password" name="password" placeholder="密码"></div><input type="submit" value="登录"></form>`
});router.get('/welcome',async ctx => {let txt = ctx.request.query;console.log(txt)let name = txt.name;let email = txt.email;let password = txt.password;ctx.body = `<h1>用户名:</h1><p>${name}</p><h1>邮箱:</h1><p>${email}</p><h1>密码:</h1><p>${password}</p>`});app.listen(3000)