一、前言
前后端分离开发比较流行,这就对本机测试带来一定麻烦,首先就是跨域问题,当前后端都部署在本机后都使用localhost域名访问就会被浏览器拦截。
这里基于phpstudy集成环境的apache服务端进行设置,解决跨域问题,同时也能解决以下两个常见的前端请求异常。
-
has been blocked by CORS policy: Response to preflight request
doesn’t pass access control check: No ‘Access-Control-Allow-Origin’
header is present on the requested resource. -
Request header field Authorization is not allowed by
Access-Control-Allow-Headers
二、使用步骤
1.修改phpstudy中的Apache配置文件
要修改的文件名为httpd.conf,其位置如图(点击打开):
在httpd.conf文件开头添加以下两行配置
Header set Access-Control-Allow-Origin *
Header set Access-Control-Allow-Headers ‘authorization,content-type,token,id’
添加配置后的文件内容如下:
Header set Access-Control-Allow-Origin *
Header set Access-Control-Allow-Headers 'authorization,content-type,token,id'
#
# This is the main Apache HTTP server configuration file. It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
# what they do. They're here only as hints or reminders. If you are unsure
# consult the online docs. You have been warned.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path. If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so "logs/access_log"
# with ServerRoot set to "/usr/local/apache2" will be interpreted by the
# server as "/usr/local/apache2/logs/access_log", whereas "/logs/access_log"
# will be interpreted as '/logs/access_log'..........
2.开启Apache配置文件的模块
在httpd.conf文件中搜索mod_headers.so,找到这行:
#LoadModule headers_module modules/mod_headers.so
将开头的#符号去掉,修改后如下图:
最后重启apache服务器即可完成
总结
本人是15年经验的全栈工程师,精通.net、java、php、python、h5、vue前端框架、iOS、Android开发,后续会出一些连载分享给大家
版权声明:本文为bluecat333原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。