最近参与一个前后端分离的项目,后端基于 .net core 2.1 开发,在进行前后端对接的过程中,被跨域问题折腾得有点脾气了,这里把经验和大家分享一下。

get/post 请求

在服务端不做任何调整的情况下,前端发起 ajax 请求,如:

$.ajax({
	type: 'get',
	url: 'http://localhost:5000',
	success: function (result) {
		$('#result').html(result);
	}
});

200 !!!好像很正常的样子,看似没毛病。但会发现 response 内屁都没有,然后回到浏览器 console 查看会有一个错误信息,提示不支持跨域访问,凉凉。

jsonp

在遇到跨域问题时很容易想到 jsonp 的解决方式,但也只限于 get 请求,post 据说比较艰难,我自己也没试用,这里就不测试了。

$.ajax({
	type: 'get',
	url: 'http://localhost:5000/home/jsonptest',
	data: {
		name: 'beck'
	},
	datatype: "jsonp",
	jsonpcallback: "jsonpcallback",
	success: function (result) {
		$('#result').html(result.data);
	}
});

那么现在问题来了,jsonp 和 get 请求毕竟有自身的一些限制,如果非要 post 怎么办?那就选择 cors 吧 !

cors

cors (cross-origin resource sharing, 跨源资源共享) 是w3c出的一个标准,其思想是使用自定义的 http 头部让浏览器与服务器进行沟通,从而决定请求或响应是应该成功,还是应该失败。cors 与 jsonp 都可以做到跨源资源共享,但与 jsonp 不同,cors 可以支持除 get 方式以外所有类型的 http 请求。

在介绍实现方式之前先简单了解部分 cors 相关的理论,不然可能对遇到的问题会有点懵,特别其中的 options 请求,明明设置的是 get、post 方式,怎么就多出一个 options 请求?

cors 请求分简单请求和复杂请求:

简单请求

同时满足以下条件的归类为简单请求:

  1. 请求方式是 head 、get、post中的一种;
  2. http的头信息不超出 accept、accept-language、content-language、last-event-id、content-type 字段;
  3. content-type 只限于 application/x-www-form-urlencoded、multipart/form-data、text/plain 三个之一;

简单请求只需要服务端设置 access-control-allow-origin 允许请求来源地址即可,我们可以在 .net core api 项目的 startup.cs 中进行如下调整:

public void configureservices(iservicecollection services)
{
	// 添加支持跨域请求
	services.addcors(); 
}

public void configure(iapplicationbuilder app, ihostingenvironment env)
{
	// 设置允许的请求来源,我本地请求发起方所在地址是 http://localhost:53894 
	app.usecors(options => options.withorigins("http://localhost:53894")); 
}

前端发起 get 或 post 请求:

$.ajax({
	type: 'post',
	url: 'http://localhost:5000/home/fromformtest',
	data: {
		name: 'beck'
	},
	success: function (result) {
		$('#result').html(result.data);
	}
});

复杂请求

不满足简单请求条件的统一归类为复杂请求,复杂请求会在正式通信之前增加一次 options 请求,称为 “预检” 请求,通过预检请求中的返回头信息,判断当前请求是否被允许。

我们可以设置 contenttype 为 application/json,此请求就变成了复杂请求:

$.ajax({
	type: 'post',
	url: 'http://localhost:5000/home/frombodytest',
	contenttype: 'application/json',
	data: json.stringify({
		name: 'beck'
	}),
	success: function (result) {
		$('#result').html(result.data);
	}
});

如果 api 项目中的 startup.cs 保持上面的调整后不变,会看到 options 请求中response headers 信息并没有出现允许请求的源地址 access-control-allow-origin ,这就代表预检失败了,继续凉凉。

这是因为在预检请求的返回头中还必须要设置 access-control-request-method 和 access-control-request-headers。app.usecors 是支持设置某些头信息或者某些请求类型,这些在使用时看实际情况而定。

public void configure(iapplicationbuilder app, ihostingenvironment env)
{
	// 设置允许的请求来源地址、头信息、请求类型
	app.usecors(options => options
		.withorigins("http://localhost:53894")
		.allowanyheader()
		.allowanymethod()
	);
}

预检通过之后,会发起 post 请求:

cookie

如果请求需要携带 cookie 到服务端,那还需要稍微做一些调整,如下:

startup.cs 增加 allowcredentials 配置:

public void configure(iapplicationbuilder app, ihostingenvironment env)
{
	// 设置允许的请求来源地址、头信息、请求类型、cookie
	app.usecors(options => options
		.withorigins("http://localhost:53894")
		.allowanyheader()
		.allowanymethod()
		.allowcredentials()
	);
}

ajax 请求中也需要增加 withcredentials 设置:

setcookie('name', 'test');
$.ajax({
	type: 'post',
	url: 'http://localhost:5000/home/frombodytest',
	contenttype: 'application/json',
	data: json.stringify({
		name: 'beck'
	}),
	xhrfields: {
		withcredentials: true
	},
	success: function (result) {
		$('#result').html(result.data);
	}
});

通过以上代码简单的修改,就实现了 cors 。在实际的内网或生产环境,可能会从运维层面通过 nginx 或者其他的设置做到不修改代码也能完美支持。

参考资料

 asp.net core cors

 corssample

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持www.887551.com。