web开发过程中跨域访问的问题


前端开发中,做接口联调时,少不了会遇到跨域访问的问题,此处记录一些遇到的问题和解决的办法。

CORS跨域

CORS(Cross-origin resource sharing),“跨域资源共享”,是一个W3C标准。它允许浏览器向跨源的服务器发送请求。CORS需要浏览器和服务器同时支持。

跨域访问的产生

当网页当前的协议,域名和端口与请求的接口或其他页面的协议、域名和端口都一致时,则它们是同源的,否则就是跨域。

目的是否跨域
协议http[https]https[http]
域名localhostlocalhost2
端口80008001是(协议和域名一致时,IE浏览器为同源)

例如,现有一个前端服务http://localhost:8000, 需要调用接口http://localhost:8001 的服务,这个时候就需要跨域的支持。此时,浏览器就会告诉我们接口调用出错了:Access to fetch at 'http://localhost:8001/api/login' from origin 'http://localhost:8000' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
在这里插入图片描述

为什么要限制跨域访问

会造成CRSF和XSS攻击。可参考https://www.cnblogs.com/lailailai/p/4528092.html。

跨域访问的通信过程

CORS的通信过程,是由浏览器自动完成的,不需要不需要用户参与:浏览器一旦发现请求跨源,就会自动添加一些附加的头信息或者多出一次附加的请求。
浏览器将CORS请求分成两类:简单请求(simple request)和非简单请求(not-so-simple request)。
浏览器发出CORS简单请求,只需要在头信息之中增加一个Origin字段,简单请求的条件如下:

  1. 请求方法是以下三种方法之一
    HEAD
    GET
    POST
  2. HTTP的头信息不超出以下几种字段:
    Accept
    Accept-Language
    Content-Language
    Last-Event-ID
    Content-Type:只限于三个值application/x-www-form-urlencoded、multipart/form-data、text/plain

浏览器发出CORS非简单请求,会在正式通信之前,增加一次HTTP查询请求,称为"预检"请求(preflight),请求方法为OPTIONS。浏览器先询问服务器,当前网页所在的域名是否在服务器的许可名单之中,以及可以使用哪些HTTP动词和头信息字段。只有当前网页的域名端口等在许可范围内,浏览器才不会拒绝数据展示。

实现

JSONP

页面中的一些标签是不做同源限制的,比如<img> <script> <style>等标签,JSONP正是利用<script>标签,把不同源的请求伪装成一个脚本请求,服务器端返回数据后,再通过回调处理。这种方式仅支持GET请求。不推荐这种方式。

响应头部修改

前端实现

请求不需要cookie时,不需要做任何改变,添加cookie时,需要配置credentials: 'include'withCredentials:true

服务端java实现

使用filter来实现,下面是一个简单的实现:
(配置项参考:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers)

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

public class CrossDomainFilter implements Filter {

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
		httpServletResponse.setCharacterEncoding("utf-8");
		chain.doFilter(request, httpServletResponse);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

	@Override
	public void destroy() {
	}
}

当请求中带有第三方cookie的时候,上述代码会出现新的问题: Access to fetch at 'http://localhost:8001/api/login' from origin 'http://localhost:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
在这里插入图片描述
此时可以将Access-Control-Allow-Origin修改为具体的域名即可解决。但是我们在开发中,可能发出请求的域名是多个,为方便开发,可以先获取请求的域名,再将Access-Control-Allow-Origin的值设置为获取的域名即可(仅限开发使用哦)。

服务端koa2-cors实现

使用nodejs做server时,可以使用koa2-cors来允许跨域访问:

	cors({
        origin: function (ctx) {
          return ctx.request.header.origin; //设置为请求的域名
        },
        credentials: true,
        allowMethods: ['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH'],
        allowHeaders: ['Content-Type', 'Authorization', 'x-requested-with'],
        exposeHeaders: ['Content-Length', 'Date', 'X-Request-Id'],
        maxAge: 1800
      })

代理

正向代理

开发服务端,页面请求同源的服务端,由服务端再请求数据返回给前端。如前端请求为http://localhost:8000,需要请求跨域的http://localhost:8001/api/login的数据:可先请求http://localhost:8000/api/login接口,由http://localhost:8000/api/login接口向http://localhost:8001/api/login请求数据并返回给页面。

反向代理

使用nginx代理,将http://localhost:8000和http://localhost:8001/api/***都使用nginx代理,如:

	...
    server {
        listen       80;
        server_name  127.0.0.1;
		location / {
			proxy_pass http://localhost:8000/;
		}
		location ^~ /api/ {
			proxy_pass http://localhost:8001/;
        }
        ...
    }

可能遇到的问题

  1. Access to fetch at 'http://localhost:8001/api/login' from origin 'http://localhost:8000' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. 设置Access-Control-Allow-Origin的值。
  2. Failed to load http://localhost:8001/apiout/sentimentAanalysis/sentiment_analysis: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:8000' is therefore not allowed access. Access-Control-Allow-Origin的值需要设置为具体的域名。
  3. 其他问题待后续补充
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值