html使用ajax访问后台接口出现跨域问题

本地html使用ajax访问后台接口出现跨域问题

场景描述:本地html项目使用ajax发送请求出现如下报错:

在这里插入图片描述

解决方案:

  1. 后端解决:示例链接

    具体方式:
    a. 使用Filter方式进行设置
    b. 继承 HandlerInterceptorAdapter
    c. 实现 WebMvcConfigurer
    d. 使用 @CrossOrgin 注解 --推荐使用
    e. 网关配置
    
  2. nginx配置

    配置如下:
    server {
    	listen 前端访问端口号;
    	server_name localhost;
    	
    	location / {
    		root   本地项目目录;
            index  访问页.html 访问页.htm;
    	}
    	# 配置代理,location后面的路径是匹配前端访问地址的
    	location /api {
    		proxy_pass  http://localhost:后端服务端口;
    	}
    
    }
    

前端访问示例:

$.ajax({
    
    
		url: "/api/test/tt",
		type: "post",
        useDefaultXhrHeader: true,
		dataType: "json",
		data:{
    
    },
		success: function (data) {
    
    
			console.log(data);
        }
	})

猜你喜欢

转载自blog.csdn.net/Shiny_boy_/article/details/126020542