前端解决跨域问题nmp安装http-server的问题

 更新时间:2022年07月25日 10:12:30   作者:BUZHOU  
这篇文章主要介绍了前端解决跨域问题-nmp安装http-server的问题,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

前端解决跨域问题-nmp安装http-server

问题背景

项目组的露露学习d3遇到问题,前端无法读取js中调用的csv文件

于是诚挚地邀请露露来了我的寝室坐坐,尝试了相对路径与绝对路径均无效,且绝对路径复制进chrome可直接下载,即文件路径没错。

右键“检查”进入开发者模式看报错,

报错:Access to XMLHttpRequest at 'file:///C:/Users/buzou/Desktop/OneNum/OneNum.csv' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.

搜索得知为跨域问题

跨域问题

跨域问题: 在本场景下,指的是侠义的跨域问题。

由浏览器同源策略限制的一类请求场景。

什么是同源策略?
同源策略/SOP(Same origin policy)是一种约定,由Netscape公司1995年引入浏览器,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,浏览器很容易受到XSS、CSFR等攻击。所谓同源是指"协议+域名+端口"三者相同,即便两个不同的域名指向同一个ip地址,也非同源。

大概看了Google的各种结果,尝试了一下两个看上去最容易的办法

尝试方法一:chrome快捷方式加” --allow-file-access-from-files“无效

尝试方法二:尝试使用nmp安装本地服务器

node.js实际上我也只是安装了但不熟悉,在配置的过程中仍然有几个坑,具体步骤跟着下面的链接来就好了:

https://jasonwatmore.com/post/2016/06/22/nodejs-setup-simple-http-server-local-web-server

(讲的全面且权威)

踩过的坑就是http-server要下载到全局,用这条命令安装npm install -g http-server

在对应的d3(前端文件)目录下输入http-server启动,会看到它给出网址,复制“127.0.0.1”这一条到浏览器,能进入服务器(后台)页面。

后记

这个写的看起来挺简单的但实际上还是卡了一个多小时,心得就是帮美女解决问题不要慌,不能心猿意马。

后续写博客记录再搜索了一下,https://zhuanlan.zhihu.com/p/130391287中写了chrome版本使用场景: 80.0.3987.163(正式版本) (64 位)可以通过指定“ --allow-file-access-from-files”来绕过跨域问题。

补充:下面看下http-server服务跨域设置问题

http-server --cors -p 9999

http-server --cors -p 9999 -c-1

--------------------------------------------------------------------------------------------------------------------------------------------------------------------

Available Options:
-p Port to use (defaults to 8080)

-a Address to use (defaults to 0.0.0.0)

-d Show directory listings (defaults to 'True')

-i Display autoIndex (defaults to 'True')

-g or --gzip When enabled (defaults to 'False') it will serve ./public/some-file.js.gzin place of ./public/some-file.js when a gzipped version of the file exists and the request accepts gzip encoding.

-e or --ext Default file extension if none supplied (defaults to 'html')

-s or --silent Suppress log messages from output

--cors Enable CORS via the Access-Control-Allow-Origin header

-o Open browser window after starting the server

-c Set cache time (in seconds) for cache-control max-age header, e.g. -c10 for 10 seconds (defaults to '3600'). To disable caching, use -c-1.

-U or --utc Use UTC time format in log messages.

-P or --proxy Proxies all requests which can't be resolved locally to the given url. e.g.: -P http://someurl.com

-S or --ssl Enable https.

-C or --cert Path to ssl cert file (default: cert.pem).

-K or --key Path to ssl key file (default: key.pem).

-r or --robots Provide a /robots.txt (whose content defaults to 'User-agent: *\nDisallow: /')

-h or --help Print this list and exit.

到此这篇关于前端解决跨域问题-nmp安装http-server的文章就介绍到这了,更多相关nmp安装http-server内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

最新评论