axios的请求传参

通过http://localhost:5000/getaward?grade=one 通过传参获取一等奖内容
image

image

第一种方式:字符串拼接

module.exports = (router) => {
    // 读取数据
    router.get('/getaward', (req, res) => {
        // 获取query参数
        let {grade} = req.query;
        //通过字符串拼接传参
        axios.get(`http://localhost:3000/content?grade=${grade}`).then(result => {
            res.send(result.data);
            // res.send('ok');
        })
    })
}

第二种方式:通过配置项进行传参

module.exports = (router) => {
    // 读取数据
    router.get('/getaward', (req, res) => {
        // 获取query参数
        let { grade } = req.query;
        // 2.通过配置项进行设置, get请求的参数放到params字段中
        axios.get('http://localhost:3000/content', {
            params: {
                grade: grade
            }
        }).then(result => {
            res.send(result.data)
        })
    })
}

注意事项:

nodejs使用axios进行http get请求时,报错TypeError [ERR_UNESCAPED_CHARACTERS]: Request path contains unescaped characters,其出现的原因是请求的url中携带中文参数

如:https://www.zhihu.com/?city=北京

posted @ 2022-06-14 20:02  秋弦  阅读(696)  评论(0编辑  收藏  举报