赞
踩
可以安装axios包,也可以引入
注意:get请求不能设置请求体,post请求可以设置请求体
post格式是 第一个参数是url,第二个参数是请求体,第三个参数是其他配置
注意: axios发起post请求,url后面的参数自动拼接到Request URL上
axios默认用get传值时用params传参,用post传值时,用data传参,就是用post传值时,url参数影响了请求地址自动加上了params
如果要解决这个问题,需要在请求开始时做一个拦截就好了
apiRequest.interceptors.request.use((request) => {
console.log(request);
if(request.method == 'post'){
request.params = {}; }
return request;
});
server.js
/* * @Description: * @Version: 2.0 * @Autor: Seven * @Date: 2021-06-09 15:59:55 * @LastEditors: Seven * @LastEditTime: 2021-07-04 18:31:19 */ const express = require("express"); const app = express(); //当浏览器url路径是/server,执行{}里的回调函数,并由response做出响应 //注意/server前没有点 ,之前一直报错 //发送请求 all代表get和post都可以 app.all("/axios", (request, response) => { //设置响应头,设置允许跨域 response.setHeader("Access-Control-Allow-Origin", "*"); /*浏览器在发送跨域请求并且包含自定义 header 字段时, 浏览器会先向服务器发送 OPTIONS 预检请求(preflight request), 探测该请求服务是否允许自定义跨域字段。 当浏览器发送接口请求出现跨域问题时,目前的做法通常会在接口服务器增加如下配置。*/ response.setHeader("Access-Control-Allow-Headers", "*"); // const data={name:"jquery发送Ajax请求"} //设置响应体 response.send("Hello Ajax"); //response.send(JSON.stringify(data)) }); //延时响应 app.get("/delay", (request, response) => { //设置响应头,设置允许跨域 response.setHeader("Access-Control-Allow-Origin", "*"); setTimeout(()=>{ //设置响应体 response.send('延时响应') },3000) }); app.listen(8000, () => { console.log("服务已经启动 8000"); });
html
<!-- * @Description: * @Version: 2.0 * @Autor: Seven * @Date: 2021-06-09 15:59:48 * @LastEditors: Seven * @LastEditTime: 2021-07-05 20:25:20 --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css" /> <script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.js"></script> </head> <body> <div class="container"> <button class="btn btn-primary">Get</button> <button class="btn btn-danger">Post</button> <button class="btn btn-info">Ajax</button> </div> <script> const btns = document.querySelectorAll("button"); //配置baseURL axios.defaults.baseURL='http://127.0.0.1:8000'; btns[0].onclick = function(){ axios.get('/axios',{ //url参数 params:{ id:123, vip:7 }, //请求头信息 headers:{ name:'m', age:12 } }).then(value=>{ console.log(value); })//.then是promise语法 }; //发送post请求 btns[1].onclick = function(){ axios.post('/axios',{ //请求体 username:'admin', password:'admin' }, { //url参数 params:{ id:123, vip:45646 }, //请求头信息 headers:{ name:'emmmm' } } ).then(value=>{ console.log(value); }) }; //Axios发送请求 btns[2].onclick=function(){ axios({ methods: 'POST', url:'/axios', params:{ vip:10, level:30 }, headers:{ a:100, b:200 }, //请求体参数 data:{ username:'admin', password:'admin' } }).then(response=>{ console.log(response); console.log(Request.methods); }) } </script> </body> </html>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。