当前位置:   article > 正文

使用Axios发送Ajax请求_微信小程序使用封装的axios发不了ajax

微信小程序使用封装的axios发不了ajax

客户端:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Axios 发送 Ajax 请求</title>
  7. <script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
  8. </head>
  9. <body>
  10. <h2>Axios 发送三种请求</h2>
  11. <button>GET</button>
  12. <button>POST</button>
  13. <button>通用方法Ajax</button>
  14. <script>
  15. const btns = document.querySelectorAll('button');
  16. //配置baseurl 对路径简化
  17. axios.defaults.baseURL = 'http://127.0.0.1:8000';
  18. btns[0].onclick = function () {
  19. console.log("test");
  20. //get 请求
  21. axios.get('/axios-server', {
  22. //和jQuery不一样
  23. //url参数
  24. params: {
  25. id: 100,
  26. vip: 10
  27. },
  28. //请求头信息
  29. headers: {
  30. name: "axio111",
  31. age: 18
  32. }
  33. }).then(value => {
  34. //这个响应是基于promise的
  35. console.log(value);
  36. });
  37. };
  38. btns[1].onclick = function () {
  39. console.log("test");
  40. //post 请求
  41. axios.post('/axios-server', {
  42. username: "admin",
  43. password: 123
  44. }, {
  45. //和jQuery不一样
  46. //url参数 行 头 体
  47. params: {
  48. id: 100,
  49. vip: 10
  50. },
  51. //请求头信息
  52. headers: {
  53. height: 172,
  54. weight: 130
  55. },
  56. });
  57. };
  58. //很清晰
  59. btns[2].onclick = function () {
  60. axios({
  61. //请求方法
  62. method: 'POST',
  63. //参数1 url
  64. url: '/axios-server',
  65. //2url 参数
  66. params: {
  67. vip: 10,
  68. level: 80
  69. },
  70. //3头信息参数
  71. headers: {
  72. a: 100,
  73. b: 200
  74. },
  75. //4请求体参数
  76. data: {
  77. username: "admin",
  78. password: 123
  79. }
  80. //then 响应结果
  81. }).then(response => {
  82. console.log(response);
  83. })
  84. };
  85. </script>
  86. </body>
  87. </html>

服务端:

  1. //Axios 服务
  2. app.all('/axios-server',(request,response)=>{
  3. //设置响应头 ('Access-Control-Allow-Origin','*');作用:允许跨域
  4. response.setHeader('Access-Control-Allow-Origin','*');
  5. response.setHeader('Access-Control-Allow-Headers','*');
  6. const data={name:'zhangsan',age:18,sex:'man'}
  7. response.send(JSON.stringify(data));
  8. });

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

闽ICP备14008679号