zoukankan      html  css  js  c++  java
  • js 调用webservice及nigix解决跨域问题

    前言

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

    答案是否定的。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端口。

  • 相关阅读:
    移动端 提交按钮呗软键盘挤上去的问题解决
    jenkins创建项目API踩坑记
    backstage使用笔记(2)- 跨域代理设置
    backstage使用笔记(1)- 项目的搭建和插件的创建
    什么是强缓存,什么是协商缓存?
    关于antd英文文案切换为中文
    记解决遇到自己电脑看线上项目没问题,别的同事电脑看线上项目有问题的疑难杂症
    vue.js组件传值
    Vue.js组件
    关于Object.keys()和for in的区别
  • 原文地址:https://www.cnblogs.com/aoximin/p/12878029.html
Copyright © 2011-2022 走看看