vue axios发送请求

分手后的思念是犯贱 2022-12-17 07:11 307阅读 0赞

baseData.js

  1. if (location.href.includes("baidu")) {
  2. apiBaseUrl = 'https://www.baidu.com';
  3. } else {
  4. apiBaseUrl = 'https://baidutest.com';
  5. }
  6. export const baseData = {
  7. apiBaseUrl: apiBaseUrl,
  8. editArticleUrl: editArticleUrl,
  9. };

http.js

  1. import axios from "axios";
  2. import { baseData } from "./baseData";
  3. let httpService = axios.create({
  4. baseURL: baseData.apiBaseUrl,
  5. timeout: 20000,
  6. });
  7. httpService.defaults.headers.common["Content-Type"] =
  8. "application/x-www-form-urlencoded";
  9. export default httpService;

util.js

  1. function getParams2(params) {
  2. let p
  3. if(location.href.includes('192.168')) {
  4. p = {...params, from_mims: 384736}
  5. }else {
  6. p = params
  7. }
  8. //参数转化
  9. let form = new FormData();
  10. Object.keys(p).forEach((key) => {
  11. form.append(key, p[key]);
  12. });
  13. return form;
  14. }

store/index.js

  1. import Vue from "vue";
  2. import Vuex from "vuex";
  3. import http from "@/utils/http";
  4. import { getParams2 } from "@/utils/utils";
  5. Vue.use(Vuex);
  6. export default new Vuex.Store({
  7. state: {},
  8. getters: {},
  9. mutations: {},
  10. actions: {
  11. getHotWord({ commit }, data) {
  12. http.post("/pc/creator/hotword", getParams2(data.params)).then((res) => {
  13. data.cb(res.data);
  14. }).catch((err) => {console.error(err, commit);});
  15. },
  16. }
  17. }

在vue组件里使用:index.vue

  1. methods: {
  2. ...mapActions(["getHotWord"]),
  3. hotWordGet() {
  4. this.getHotWord({
  5. params: {},
  6. cb: (res) => {
  7. if (res.return_code == 200) {
  8. this.hotSearchWords = res.return_data;
  9. } else {
  10. ///错误处理
  11. }
  12. },
  13. });
  14. }
  15. }

发表评论

表情:
评论列表 (有 0 条评论,307人围观)

还没有评论,来说两句吧...

相关阅读