首页 > Web开发 > 详细

js 调用webservice及nigix解决跨域问题

时间:2020-05-12 21:30:29      阅读:70      评论:0      收藏:0      [点我收藏+]

前言

我们写一些简单的爬虫的时候会遇到跨域问题,难道我们一定要用后台代理去解决吗?

答案是否定的。python之所以适应爬虫,是因为库真的很好用。

好吧python不是今天的主角,今天的主角是js。

正文

因为api的很简单,所以我这里写webservice的,因为有时候你可能会遇到webservice,当然这是一些老项目了。

这是里面的webservice的一个方法:

[WebMethod]
public int sum(int a,int b)
{
     return a + b; 
}

下面是文档:

技术分享图片

接下来就是如何去调用他:

function RequestWebService() {
	let data = `<?xml version="1.0" encoding="utf-8"?>
	<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
	   <soap12:Body>
		   <sum xmlns="http://tempuri.org/">
				<a>1</a>
				<b>5</b>
		   </sum>
		 </soap12:Body>
	</soap12:Envelope>`;
	$.ajax({
		headers: { SOAPAction: ‘http://tempuri.org/sum‘ },
		contentType: ‘text/xml;charset="UTF-8"‘,
		dataType: ‘xml‘,
		type: ‘post‘,
		url: ‘http://localhost:10050/myWebServie.asmx‘,
		data: data,
		success: function (data) {
			console.log(data);
		}
	});
}

然后获得了:

<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<sumResponse xmlns="http://tempuri.org/">
<sumResult>6</sumResult>
</sumResponse>
</soap:Body>
</soap:Envelope>

但是呢,这个html是和webservice在同一个端口下,那么不同端口肯定会出现跨域问题。

技术分享图片

请求数据:
技术分享图片

那么这个时候怎么破呢?

在nginx配置下面:

location /myWebServie.asmx {
	proxy_pass http://localhost:10050/myWebServie.asmx
}

然后将页面部署到nginx下面的8085端口下;

然后你在页面中访问的就是:http://localhost:8085/myWebServie.asmx

效果:

技术分享图片

返回结果就是200了。

原理非常简单,我们这样做可以骗过浏览器,以为我们访问的是8085端口,实际上访问的到nginx的时候访问的是10050端口。

js 调用webservice及nigix解决跨域问题

原文:https://www.cnblogs.com/aoximin/p/12878029.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!