跨域问题

跨域问题

1.是什么:

A网站(恶意网站) --> B服务(没有允许A的访问)

如果A使用脚本的方式模拟用户去请求B, 就会被浏览器拦截

2.拦截过程:

  • 普通请求: get. post等请求, 浏览器直接执行跨域请求, 但是会拦截请求检查跨域配置, 如果不通过就不展示结果
  • 复杂请求: del put等先发送option请求

3.案例

测试前端:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>跨域请求示例</h1>
<button onclick="fetchData()">发送请求</button>
<pre id="result"></pre>

<script>
    function fetchData() {
        fetch('http://localhost:8080/user/test')
            .then(response => response.json())
            .then(data => {
                document.getElementById('result').textContent = JSON.stringify(data, null, 2);
            })
            .catch(error => {
                console.error('出错了:', error);
            });
    }
</script>
</body>
</html>

后端:

@RestController
@RequestMapping("/user")
public class UserController {
    @GetMapping("/test")
    public String test() {
        return "{\"msg\": \"request ok\"}";
    }
}

请求可以进来正如上面普通拦截, 但是浏览器并没有展示而是报错了

正常结果:

4.解决跨域

4.1 @CrossOrigin("*")

4.2 全局配置

@Configuration
public class webConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTION")
                .allowedHeaders("*");
    }
}

4.3 nginx

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇