本地搭建前后端分离项目,解决跨域问题(has been blocked by CORS policy: No ‘Access-Control-Allow-Origin)

楔子:

跨域的定义:域名,端口,协议,只要有一个不同,就算跨域。

http://www.123.com/index.html 调用 http://www.123.com/server.php (非跨域)

http://www.123.com/index.html 调用 http://www.456.com/server.php (主域名不同:123/456,跨域)

http://abc.123.com/index.html 调用 http://def.123.com/server.php (子域名不同:abc/def,跨域)

http://www.123.com:8080/index.html 调用 http://www.123.com:8081/server.php (端口不同:8080/8081,跨域)

http://www.123.com/index.html 调用 https://www.123.com/server.php (协议不同:http/https,跨域)

浏览器限制跨域:浏览器正常发送请求,服务器正常响应(200),但是浏览器不会显示数据

问题背景:

本地搭建了 springboot (8080端口) 后端项目和 react (3000端口)前端项目,想在前端中用axios发get请求调用后端接口

import React, { Component } from 'react'
import Axios from 'axios'

// axios 发送请求
export default class App extends Component {

    url = 'http://localhost:8080/books/all';

    // 发送请求:在挂载周期中发送

    componentDidMount(){
        // 获取所有书籍  all
        Axios.get(this.url).then((response) => {
            console.log(response);
        });
    }

  render() {
    return (
      <div>
        发送 axios 请求
      </div>
    )
  }
}

浏览器报了如下错误:
在这里插入图片描述
意思是:cors (“跨域资源共享”(Cross-origin resource sharing)) 阻止了你请求的资源

问题原因:

前后端项目在不同的端口上,出现了跨域问题,被浏览器限制。

解决方法:

1、后端项目中配置一个config文件

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
                // 允许跨域请求的地址
        registry.addMapping("/**")
                // 允许跨域请求的域名
                .allowedOriginPatterns("*")
                // 允许的请求方法
                .allowedMethods("GET","POST","PUT","OPTIONS","DELETE","PATCH")
                // 是否允许证书(cookies)
                .allowCredentials(true)
                // 跨域允许时间
                .maxAge(3600);
    }
}

注意: 如果设置了 allowCredentials(true) ,则不能使用allowedOrigin("") ,要换成 allowedOriginPatterns(""),否则springboot会报如下错误:

When allowCredentials is true, allowedOrigins cannot contain the special value "*“since that cannot be set on the “Access-Control-Allow-Origin” response header. To allow credentials to a set of origins, list them explicitly or consider using"allowedOriginPatterns” instead.

此方法可行:
在这里插入图片描述

2、nginx代理

没调通,待完善  ̄□ ̄||

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Systemd

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值