axios请求接口,请求了两次的解决方案

大家是否遇到过这种情况,使用axios请求一个接口时,请求了两次
在这里插入图片描述
在这里插入图片描述
分别 了options请求及我们期待的post请求。
这里只讲述解决办法,至于为啥多出了个options请求,有兴趣的自行百度了解。

解决办法:
步骤一:
设置axios的请求头的"Content-Type"为"application/x-www-form-urlencoded;charset=UTF-8"

axios.defaults.headers["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8";

步骤二:
请求参数的载体使用URLSearchParams

  const params = new URLSearchParams();
  params.append(key, value);
  axios.post(url, url_params);

OK~,仅需两个步骤即可优化两次的请求

猜你喜欢

转载自blog.csdn.net/u010775335/article/details/127409327