前后端分离项目有两种部署方式:
一、同网站部署,在前端iis网站下,新建应用程序;如:api,接口用域名+/api访问。
二、前后端项目分开部署,两个域名不同会遇到跨域问题,下面就详细说下解决方式;
CORS将请求分为两种:
简单请求:
请求方式:post、get、head
头部字段满足cors安全规范,详见W3C,可默认,若有自定义head字段,需要后台配置允许;
请求头的Content-Type为:1,text/plain 2,nultipart/form-data 3,application/x-www-form-urlencoded
复杂请求:非简单请求
后端代码:web.config 中配置
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://vue.test.com" />前端访问域名
<add name="Access-Control-Allow-Headers" value="Accept,token, Origin, x-www-form-urlencoded, Content-Type,Last-Modified,x-requested-with" />允许访问请求头
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />请求方式
<add name="Access-Control-Allow-Credentials" value="true" /> <!--前端:withCredentials: true, // 跨域请求时发送Cookie-->如后端需要存cookie,则需要配置这个
</customHeaders>
</httpProtocol>
前端vue里面配置:
import axios from "axios";
import QS from 'qs';
axios.defaults.headers.post["Content-Type"] = "text/plain";
import {
Message
} from 'element-ui';``
import router from '@/router/index.js'
const flagUrl = window.location.href.includes('localhost')
const http = axios.create({
baseURL: flagUrl ? 'http://localhost:8080' :'https://net.test.com', //域名
withCredentials: true, // 跨域请求时发送Cookie,否则后台无法获取cookie值
timeout: 5000, //响应时间
})