美文网首页
axios的参数传递?

axios的参数传递?

作者: 布卡卡的晴空 | 来源:发表于2020-02-25 23:34 被阅读0次
  • get和 delete请求传递参数,他俩传参请求形式一样
    发送请求
   //    发送get 请求
      axios.get("http://localhost:3000/axios").then(function(ret) {
        // data 为固定的,用于获取后台数据
        console.log(ret.data);
      });
  • 通过传统的url 以 ? 的形式传递参数
        axios.get("http://localhost:3000/axios?id=123").then(function(ret) {
          // data 为固定的,用于获取后台数据
          console.log(ret.data);
        });

后端api写法,通过req.query

app.get("/axios", (req, res) => {
  res.send("传递参数  " + req.query.id);
});
  • restful 形式传递参数
     axios.get("http://localhost:3000/axios/123").then(function(ret) {
          // data 为固定的,用于获取后台数据
          console.log(ret.data);
        });

后端api写法,通过req.params

app.get("/axios/:id", (req, res) => {
  res.send("传递参数  " + req.params.id);
});
  • 通过params 形式传递参数
      axios
        .get("http://localhost:3000/axios", {
          params: {
            id: 456
          }
        })
        .then(function(ret) {
          // data 为固定的,用于获取后台数据
          console.log(ret.data);
        });

后端api写法,通过req.query

app.get("/axios", (req, res) => {
  res.send("传递参数  " + req.query.id);
});
  • post 和 put 请求传递参数
    • 通过选项传递参数
    axios.post('http://localhost:3000/axios', {
      uname: 'lisi',
      pwd: 123
    }).then(function(ret){
      console.log(ret.data)
    })

后端api写法,通过req.body

app.post("/axios", (req, res) => {
  res.send("axios post 传递参数" + req.body.uname + "---" + req.body.pwd);
});
  • 通过 URLSearchParams 传递参数
    var params = new URLSearchParams();
    params.append('uname', 'zhangsan');
    params.append('pwd', '111');
    axios.post('http://localhost:3000/axios', params).then(function(ret){
      console.log(ret.data)
    })

后端api写法,通过req.body

app.post("/axios", (req, res) => {
  res.send("axios post 传递参数" + req.body.uname + "---" + req.body.pwd);
});

注意:restful风格传递参数后端用req.params,
params对象后端用req.query接收,一般put和post都用req.body,get和delete都用req.query

相关文章

网友评论

      本文标题:axios的参数传递?

      本文链接:https://www.haomeiwen.com/subject/typgchtx.html