2022年10月25日

跨域问题只存在于浏览器中,其他平台不存在跨域问题。

uniapp 调试时的跨域解决方案

方法一:manifest.json中配置代理服务

  1. "h5": {
  2. "devServer": {
  3. "https": false,
  4. "proxy": {
  5. "/api": {
  6. "target": "http://xinchang.jzy.jkmmm.com", //自己项目接口域名
  7. "changeOrigin": true, //是否跨域
  8. "secure": false, // 设置支持https协议的代理
  9. "pathRewrite": {
  10. "^/api": ""
  11. } //api路径重定向,根据具体情况调整,也可不写
  12. }
  13. }
  14. }
  15. }
  1. uni.request({
  2. 'method': 'POST',
  3. 'url': '/api/user_construct/get_decorations_list', // 请求域名后面的部分地址即可
  4. 'data': {
  5. "site_id": 1507,
  6. "be_from": "h5",
  7. "page": 1,
  8. "sort": 2
  9. }
  10. });

方法二:创建vue.config.js文件,并在里面配置devServer

  1. module.exports = {
  2. devServer: {
  3. proxy: {
  4. '/prefix': {
  5. target: 'https://api-remote.xxxx.com',
  6. pathRewrite: {
  7. '^/prefix': ''
  8. }
  9. }
  10. },
  11. }
  12. }

部署时的跨域解决方案

方案1:最利索的,当然还是将前端代码和后端接口部署在同域的web服务器上。
方案2:由后台服务器配置策略,设为允许跨域访问。

thinkPHP5

  1. // index.php 入口文件中添加
  2. // OPTION请求支持跨域
  3. if($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  4. header("Access-Control-Allow-Origin: *");
  5. header("Access-Control-Allow-Headers: *");
  6. header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH');
  7. exit();
  8. }
  9. // GET POST请求支持跨域
  10. header("Access-Control-Allow-Origin: *");
  11. header("Access-Control-Allow-Headers: *");
  12. header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH');

eggjs

  1. // 1、安装egg-cors包
  2. npm i egg-cors --save
  3. // 2、在plugin.js中设置开启cors
  4. exports.cors = {
  5. enable: true,
  6. package: 'egg-cors',
  7. };
  8. // 3、在config.default.js中配置
  9. config.security = {
  10. domainWhiteList: [ '前端网页托管的域名' ],
  11. };

(完)