当前位置:   article > 正文

11 ajax 和 axios_axios processdata

axios processdata

前言

加更 ... 

测试用例

ajax 发送请求 

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>01Jquery</title>
  6. </head>
  7. <body>
  8. <span id="resp">
  9. </span>
  10. <script src="../js/jquery.min.js" type="text/javascript"></script>
  11. <script>
  12. // When data is an object, jQuery generates the data string from the object's key/value pairs unless the processData option is set to false. For example, { a: "bc", d: "e,f" } is converted to the string "a=bc&d=e%2Cf"
  13. $.ajax({
  14. url: "/HelloWorld/listForm",
  15. type: "POST",
  16. contentType : "application/x-www-form-urlencoded",
  17. headers : {
  18. "header01" : "thisIsHeader01",
  19. "header02" : "thisIsHeader02"
  20. },
  21. data : {
  22. param01 : "thisIsParam01",
  23. param02 : "thisIsParam02"
  24. },
  25. success: function (result) {
  26. $("#resp").text(JSON.stringify(result))
  27. }
  28. });
  29. // $.ajax({
  30. // url: "/HelloWorld/listJson",
  31. // type: "POST",
  32. // contentType: "application/json",
  33. // headers: {
  34. // "header01": "thisIsHeader01",
  35. // "header02": "thisIsHeader02"
  36. // },
  37. // data: JSON.stringify({
  38. // param01: "thisIsParam01",
  39. // param02: "thisIsParam02"
  40. // }),
  41. // success: function (result) {
  42. // $("#resp").text(JSON.stringify(result))
  43. // }
  44. // });
  45. </script>
  46. </body>
  47. </html>

axios 发送请求 

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>02Axios</title>
  6. </head>
  7. <body>
  8. <span id="resp">
  9. </span>
  10. <script src="../js/axios.min.js" type="text/javascript"></script>
  11. <script>
  12. // interceptors
  13. axios.interceptors.request.use(function (config) {
  14. // 拦截 request, 处理请求
  15. console.log("do sth before send request, config : ", config)
  16. return config;
  17. }, function (error) {
  18. return Promise.reject(error);
  19. });
  20. axios.interceptors.response.use(function (response) {
  21. // 拦截 response, 处理响应
  22. console.log("do sth before receive response, response : ", response)
  23. return response.data;
  24. }, function (error) {
  25. return Promise.reject(error);
  26. });
  27. // 默认情况下,axios将JavaScript对象序列化为JSON。 要以application / x-www-form-urlencoded格式发送数据,您可以使用以下选项之一。
  28. const formEncoded = new URLSearchParams()
  29. formEncoded.append("param01", "thisIsParam01")
  30. formEncoded.append("param02", "thisIsParam02")
  31. const rawForms = {
  32. param01: "thisIsParam01",
  33. param02: "thisIsParam02"
  34. }
  35. axios.request({
  36. url: "/HelloWorld/listForm",
  37. method: "post",
  38. headers: {
  39. "header01": "thisIsHeader01",
  40. "header02": "thisIsHeader02",
  41. 'Content-Type': 'application/x-www-form-urlencoded'
  42. },
  43. data: formEncoded
  44. })
  45. .then(function (fullResp) {
  46. // let resp = fullResp.data
  47. let resp = fullResp
  48. document.getElementById("resp").innerText = JSON.stringify(resp)
  49. })
  50. // axios.request({
  51. // url: "/HelloWorld/listJson",
  52. // method: "post",
  53. // headers: {
  54. // "header01": "thisIsHeader01",
  55. // "header02": "thisIsHeader02",
  56. // 'Content-Type': 'application/json'
  57. // },
  58. // data: {
  59. // param01: "thisIsParam01",
  60. // param02: "thisIsParam02"
  61. // }
  62. // })
  63. // .then(function (fullResp) {
  64. // //let resp = fullResp.data
  65. // let resp = fullResp
  66. // document.getElementById("resp").innerText = JSON.stringify(resp)
  67. // })
  68. </script>
  69. </body>
  70. </html>

处理以上请求的后端服务, 简单的处理, 获取到请求头 和 参数, 然后 响应给客户端 

通过 @RequesParam[request.getParameter("$paramName")], 或者 @RequestBody 来获取参数 

通过 @RequestHeader 来获取请求头 

  1. /**
  2. * HelloWorldController
  3. *
  4. * @author Jerry.X.He <970655147@qq.com>
  5. * @version 1.0
  6. * @date 2022-02-27 21:21
  7. */
  8. @RestController
  9. @RequestMapping("/HelloWorld")
  10. public class HelloWorldController {
  11. @RequestMapping("/listForm")
  12. public List<JSONObject> listForm(
  13. @RequestHeader("header01") String header01,
  14. @RequestHeader("header02") String header02,
  15. String param01,
  16. String param02
  17. ) {
  18. List<JSONObject> result = new ArrayList<>();
  19. result.add(wrapEntity("header01", header01));
  20. result.add(wrapEntity("header02", header02));
  21. result.add(wrapEntity("param01", param01));
  22. result.add(wrapEntity("param02", param02));
  23. return result;
  24. }
  25. @RequestMapping("/listJson")
  26. public List<JSONObject> listJson(
  27. @RequestHeader("header01") String header01,
  28. @RequestHeader("header02") String header02,
  29. @RequestBody JSONObject param01
  30. ) {
  31. List<JSONObject> result = new ArrayList<>();
  32. result.add(wrapEntity("header01", header01));
  33. result.add(wrapEntity("header02", header02));
  34. result.add(wrapEntity("param01", JSON.toJSONString(param01)));
  35. return result;
  36. }
  37. // wrapEntity
  38. public JSONObject wrapEntity(String name, String age) {
  39. JSONObject result = new JSONObject();
  40. result.put("name", name);
  41. result.put("age", age);
  42. return result;
  43. }
  44. }

http 请求 和 http 响应

http 请求包含了三部分, 请求行, 请求头, 请求体 

请求行是第一行, 包含了 请求方法, uri, http协议版本 

请求行 和 请求头 通过 换行回车 分割, 接下来的 Host, Connection, 等等属于请求头 

请求体 和 请求头之间通过 两个换行回车分割, "param01=thisIsParam01¶m02=thisIsParam02" 属于请求体 

  1. POST /HelloWorld/listForm HTTP/1.1
  2. Host: localhost
  3. Connection: keep-alive
  4. Content-Length: 43
  5. Pragma: no-cache
  6. Cache-Control: no-cache
  7. sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="99", "Google Chrome";v="99"
  8. header01: thisIsHeader01
  9. sec-ch-ua-mobile: ?0
  10. User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.45 Safari/537.36
  11. Content-Type: application/x-www-form-urlencoded
  12. Accept: */*
  13. X-Requested-With: XMLHttpRequest
  14. sec-ch-ua-platform: "macOS"
  15. header02: thisIsHeader02
  16. Origin: http://localhost
  17. Sec-Fetch-Site: same-origin
  18. Sec-Fetch-Mode: cors
  19. Sec-Fetch-Dest: empty
  20. Referer: http://localhost/httpClient/01Jquery.html
  21. Accept-Encoding: gzip, deflate, br
  22. Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7
  23. Cookie: XXL_JOB_LOGIN_IDENTITY=7b226964223a312c22757365726e616d65223a2261646d696e222c2270617373776f7264223a226531306164633339343962613539616262653536653035376632306638383365222c22726f6c65223a312c227065726d697373696f6e223a6e756c6c7d
  24. param01=thisIsParam01&param02=thisIsParam02

http 响应包含了三部分, 状态行, 响应头, 响应体 

和上面 http 请求的结构类似, 不过状态行 是包含的是 http协议版本 加上 状态码 

  1. HTTP/1.1 200
  2. Server: nginx/1.19.9
  3. Date: Mon, 28 Feb 2022 12:57:10 GMT
  4. Content-Type: application/json;charset=UTF-8
  5. Transfer-Encoding: chunked
  6. Connection: keep-alive
  7. backendIP: 192.168.31.184:8080
  8. b0
  9. [{"name":"header01","age":"thisIsHeader01"},{"name":"header02","age":"thisIsHeader02"},{"name":"param01","age":"{\"param01\":\"thisIsParam01\",\"param02\":\"thisIsParam02\"}"}]
  10. 0

form表单 传递参数 

ajax 配置 contentType 为 application/x-www-form-urlencoded, 然后参数直接放到 data 中即可 

默认 jquery 会将参数处理为 表单参数格式

  1. // When data is an object, jQuery generates the data string from the object's key/value pairs unless the processData option is set to false. For example, { a: "bc", d: "e,f" } is converted to the string "a=bc&d=e%2Cf"
  2. $.ajax({
  3. url: "/HelloWorld/listForm",
  4. type: "POST",
  5. contentType : "application/x-www-form-urlencoded",
  6. headers : {
  7. "header01" : "thisIsHeader01",
  8. "header02" : "thisIsHeader02"
  9. },
  10. data : {
  11. param01 : "thisIsParam01",
  12. param02 : "thisIsParam02"
  13. },
  14. success: function (result) {
  15. $("#resp").text(JSON.stringify(result))
  16. }
  17. });

发送给服务器的 http 请求为 

  1. POST /HelloWorld/listForm HTTP/1.1
  2. Host: localhost
  3. Connection: keep-alive
  4. Content-Length: 43
  5. Pragma: no-cache
  6. Cache-Control: no-cache
  7. sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="99", "Google Chrome";v="99"
  8. header01: thisIsHeader01
  9. sec-ch-ua-mobile: ?0
  10. User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.45 Safari/537.36
  11. Content-Type: application/x-www-form-urlencoded
  12. Accept: */*
  13. X-Requested-With: XMLHttpRequest
  14. sec-ch-ua-platform: "macOS"
  15. header02: thisIsHeader02
  16. Origin: http://localhost
  17. Sec-Fetch-Site: same-origin
  18. Sec-Fetch-Mode: cors
  19. Sec-Fetch-Dest: empty
  20. Referer: http://localhost/httpClient/01Jquery.html
  21. Accept-Encoding: gzip, deflate, br
  22. Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7
  23. Cookie: XXL_JOB_LOGIN_IDENTITY=7b226964223a312c22757365726e616d65223a2261646d696e222c2270617373776f7264223a226531306164633339343962613539616262653536653035376632306638383365222c22726f6c65223a312c227065726d697373696f6e223a6e756c6c7d
  24. param01=thisIsParam01&param02=thisIsParam02

浏览器中效果如下 

axios 这边默认是序列化为 json, 需要表单格式, 要表单格式的话, 需要手动转换[有 URLSearchParams 相关api]

  1. // 默认情况下,axios将JavaScript对象序列化为JSON。 要以application / x-www-form-urlencoded格式发送数据,您可以使用以下选项之一。
  2. const formEncoded = new URLSearchParams()
  3. formEncoded.append("param01", "thisIsParam01")
  4. formEncoded.append("param02", "thisIsParam02")
  5. const rawForms = {
  6. param01: "thisIsParam01",
  7. param02: "thisIsParam02"
  8. }
  9. axios.request({
  10. url: "/HelloWorld/listForm",
  11. method: "post",
  12. headers: {
  13. "header01": "thisIsHeader01",
  14. "header02": "thisIsHeader02",
  15. 'Content-Type': 'application/x-www-form-urlencoded'
  16. },
  17. data: formEncoded
  18. })
  19. .then(function (fullResp) {
  20. // let resp = fullResp.data
  21. let resp = fullResp
  22. document.getElementById("resp").innerText = JSON.stringify(resp)
  23. })

发送给服务器的 http 请求为 

  1. POST /HelloWorld/listForm HTTP/1.1
  2. Host: localhost
  3. Connection: keep-alive
  4. Content-Length: 43
  5. Pragma: no-cache
  6. Cache-Control: no-cache
  7. sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="99", "Google Chrome";v="99"
  8. header01: thisIsHeader01
  9. sec-ch-ua-mobile: ?0
  10. User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.45 Safari/537.36
  11. Content-Type: application/x-www-form-urlencoded
  12. Accept: application/json, text/plain, */*
  13. sec-ch-ua-platform: "macOS"
  14. header02: thisIsHeader02
  15. Origin: http://localhost
  16. Sec-Fetch-Site: same-origin
  17. Sec-Fetch-Mode: cors
  18. Sec-Fetch-Dest: empty
  19. Referer: http://localhost/httpClient/02Axios.html
  20. Accept-Encoding: gzip, deflate, br
  21. Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7
  22. Cookie: XXL_JOB_LOGIN_IDENTITY=7b226964223a312c22757365726e616d65223a2261646d696e222c2270617373776f7264223a226531306164633339343962613539616262653536653035376632306638383365222c22726f6c65223a312c227065726d697373696f6e223a6e756c6c7d
  23. param01=thisIsParam01&param02=thisIsParam02

浏览器中效果如下 

application/json 传递参数 

ajax 配置 contentType 为 application/json,  默认 jquery 会将参数处理为 表单参数格式, 所以需要将参数手动处理为 json 字符串, 这里是基于 JSON.stringify 

  1. $.ajax({
  2. url: "/HelloWorld/listJson",
  3. type: "POST",
  4. contentType: "application/json",
  5. headers: {
  6. "header01": "thisIsHeader01",
  7. "header02": "thisIsHeader02"
  8. },
  9. data: JSON.stringify({
  10. param01: "thisIsParam01",
  11. param02: "thisIsParam02"
  12. }),
  13. success: function (result) {
  14. $("#resp").text(JSON.stringify(result))
  15. }
  16. });

发送给服务器的 http 请求为 

  1. POST /HelloWorld/listJson HTTP/1.1
  2. Host: localhost
  3. Connection: keep-alive
  4. Content-Length: 53
  5. Pragma: no-cache
  6. Cache-Control: no-cache
  7. sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="99", "Google Chrome";v="99"
  8. header01: thisIsHeader01
  9. sec-ch-ua-mobile: ?0
  10. User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.45 Safari/537.36
  11. Content-Type: application/json
  12. Accept: */*
  13. X-Requested-With: XMLHttpRequest
  14. sec-ch-ua-platform: "macOS"
  15. header02: thisIsHeader02
  16. Origin: http://localhost
  17. Sec-Fetch-Site: same-origin
  18. Sec-Fetch-Mode: cors
  19. Sec-Fetch-Dest: empty
  20. Referer: http://localhost/httpClient/01Jquery.html
  21. Accept-Encoding: gzip, deflate, br
  22. Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7
  23. Cookie: XXL_JOB_LOGIN_IDENTITY=7b226964223a312c22757365726e616d65223a2261646d696e222c2270617373776f7264223a226531306164633339343962613539616262653536653035376632306638383365222c22726f6c65223a312c227065726d697373696f6e223a6e756c6c7d
  24. {"param01":"thisIsParam01","param02":"thisIsParam02"}

浏览器中效果如下 

axios 这边默认是序列化为 json, 不用做任何转化 

  1. axios.request({
  2. url: "/HelloWorld/listJson",
  3. method: "post",
  4. headers: {
  5. "header01": "thisIsHeader01",
  6. "header02": "thisIsHeader02",
  7. 'Content-Type': 'application/json'
  8. },
  9. data: {
  10. param01: "thisIsParam01",
  11. param02: "thisIsParam02"
  12. }
  13. })
  14. .then(function (fullResp) {
  15. let resp = fullResp.data
  16. // let resp = fullResp
  17. document.getElementById("resp").innerText = JSON.stringify(resp)
  18. })

发送给服务器的 http 请求为 

  1. POST /HelloWorld/listJson HTTP/1.1
  2. Host: localhost
  3. Connection: keep-alive
  4. Content-Length: 53
  5. Pragma: no-cache
  6. Cache-Control: no-cache
  7. sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="99", "Google Chrome";v="99"
  8. header01: thisIsHeader01
  9. sec-ch-ua-mobile: ?0
  10. User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.45 Safari/537.36
  11. Content-Type: application/json
  12. Accept: application/json, text/plain, */*
  13. sec-ch-ua-platform: "macOS"
  14. header02: thisIsHeader02
  15. Origin: http://localhost
  16. Sec-Fetch-Site: same-origin
  17. Sec-Fetch-Mode: cors
  18. Sec-Fetch-Dest: empty
  19. Referer: http://localhost/httpClient/02Axios.html
  20. Accept-Encoding: gzip, deflate, br
  21. Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7
  22. Cookie: XXL_JOB_LOGIN_IDENTITY=7b226964223a312c22757365726e616d65223a2261646d696e222c2270617373776f7264223a226531306164633339343962613539616262653536653035376632306638383365222c22726f6c65223a312c227065726d697373696f6e223a6e756c6c7d
  23. {"param01":"thisIsParam01","param02":"thisIsParam02"}

浏览器中效果如下 

axios 的拦截器 

呵呵 常规的拦截处理, 在发送请求之前对于请求的统一转换处理, 以及在收到响应之后, 对于响应的统一转换处理 

这里 response 拦截处理, 直接获取了 reponse.data, 那么业务这边拿到的就是 reponse.data 

  1. // interceptors
  2. axios.interceptors.request.use(function (config) {
  3. // 拦截 request, 处理请求
  4. console.log("do sth before send request, config : ", config)
  5. return config;
  6. }, function (error) {
  7. return Promise.reject(error);
  8. });
  9. axios.interceptors.response.use(function (response) {
  10. // 拦截 response, 处理响应
  11. console.log("do sth before receive response, response : ", response)
  12. return response.data;
  13. }, function (error) {
  14. return Promise.reject(error);
  15. });

下面的 then, 回调处理 拿到的 fullResp 即为服务端返回的响应数据, 而不是 axios 本身封装的一层 响应实体了 

可以和上面没有加 axios 拦截器的场景进行参照对比一下 

  1. axios.request({
  2. url: "/HelloWorld/listJson",
  3. method: "post",
  4. headers: {
  5. "header01": "thisIsHeader01",
  6. "header02": "thisIsHeader02",
  7. 'Content-Type': 'application/json'
  8. },
  9. data: {
  10. param01: "thisIsParam01",
  11. param02: "thisIsParam02"
  12. }
  13. })
  14. .then(function (fullResp) {
  15. // let resp = fullResp.data
  16. let resp = fullResp
  17. document.getElementById("resp").innerText = JSON.stringify(resp)
  18. })

整个网关流程梳理

本测试用例基于 nginx 来提供前端服务, 以及代理后端服务 

nginx 服务器的 docker-compose 如下, 配置了容器中的 root目录 挂载在 宿主机的 "/Users/jerry/WebstormProjects/HelloWorld", 然后 "http://localhost/httpClient/01Jquery.html" 访问的就是 "/Users/jerry/WebstormProjects/HelloWorld/httpClient/01Jquery.html" 

  1. version: "2"
  2. services:
  3. nginx:
  4. container_name: nginx
  5. image: nginx:latest
  6. ports:
  7. - "80:80"
  8. volumes:
  9. - ./data:/etc/nginx
  10. # - ./html:/usr/share/nginx/html
  11. - /Users/jerry/WebstormProjects/HelloWorld:/usr/share/nginx/html

项目目录结构如下

nginx 配置文件如下 

root目录 对应的是容器中的 /usr/share/nginx/html, 对应于挂载在宿主机的 /Users/jerry/WebstormProjects/HelloWorld 

配置了 "/HelloWorld" 打头的服务, 转发到 192.168.31.184:8080, 也就是我们的后端服务 

上面测试的 "/HelloWorld/listForm", "/HelloWorld/listJson" 都是会转发到 192.168.31.184:8080 

  1. server {
  2. listen 80;
  3. listen [::]:80;
  4. server_name localhost;
  5. #charset koi8-r;
  6. #access_log /var/log/nginx/host.access.log main;
  7. location / {
  8. root /usr/share/nginx/html;
  9. index index.html index.htm;
  10. }
  11. location ~ /HelloWorld {
  12. proxy_pass http://192.168.31.184:8080;
  13. add_header backendIP $upstream_addr;
  14. proxy_set_header SSL-Client-Cert $ssl_client_cert;
  15. proxy_set_header name jerry;
  16. }
  17. #error_page 404 /404.html;
  18. # redirect server error pages to the static page /50x.html
  19. #
  20. error_page 500 502 503 504 /50x.html;
  21. location = /50x.html {
  22. root /usr/share/nginx/html;
  23. }
  24. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/157503
推荐阅读
相关标签
  

闽ICP备14008679号