关于后端允许跨域后,axios的post请求仍显示跨域问题

时间:2025-03-09 19:45:49

文章目录

  • 问题
  • 解决

问题

我们后端 PHP 已经设置了允许跨域:

header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods:POST, GET, OPTIONS');
  • 1
  • 2

但我们用 axios 进行 post 请求时仍会显示跨域

axios.post("请求路径",{
		name: 'zhangsan',
		age: 23
	})
     .then(function(response){
     	console.info(response.data);
      })
     .catch(function(error){
         console.info(error);
      })   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

注: 使用上述post方式提交参数的时候存在问题,大多数服务器只能识别 form 的 post 的请求,即请求头 Content-Type 为 application/x-www-form-urlencoded
 jquery 的 ajax 的 post 的 Content-Type 是 application/x-www-form-urlencoded
 axios 的 Content-Type 是 application/json

而上述 axios 默认传参的是 application/json:JSON数据格式
  {name:“zhangsan”,age:10}
我们需要将它转换为 application/x-www-form-urlencoded :form-data格式发送到服务器
  name=“zhangsan”&age=10

解决

此时我们需要将数据格式作转换,在当前页面引入第三方库qs

npm install qs  //安装qs

import Qs from "qs"		//引入qs
  • 1

<!-- 通过cdn引入 -->
<script src="/qs/6.9.0/"></script>
  • 1
  • 2

用 () 对数据进行格式转换

axios.post("请求路径",qs.stringify({
		name: 'zhangsan',
		age: 23
	}))
     .then(function(response){
     	console.info(response.data);
      })
     .catch(function(error){
         console.info(error);
      })   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10