定义了一个JS文件,在HTML中模块引入,运行index.html文件
浏览器控制台报以下错误(跨域)
为什么跨域???
导致跨域的原因:协议、域名、端口号只要有一个不同就会导致跨域,而协议通常是指http协议、https等协议,也就是说http、data、chrome、chrome-extension、https这些协议支持跨域请求,但file协议并不支持。(script标签是自带跨域功能的,这也就是我们在某些场合会通过jsonp并结合script来请求资源的原因。)
浏览器通过file协议和http协议去访问文件(file:///文件路径和http://访问路径)的区别:
- file协议用于访问本地计算机的文件,好比通过资源管理器打开文件一样,需要注意的是它是针对本地的,即file协议是访问本机的文件资源。
- http协议访问本地的html文件,相当于将本机作为一台http服务器,然后通过localhost访问的是本地服务器,再通过http服务器去访问本机的文件资源。
- 通俗说,file协议只是简单请求本地文件,将其作为一个服务器未解析的静态文件打开;而http是在本地搭建一个服务器再通过服务器解析打开文件
例如:当在本机直接打开一个网页index.html,该网页通过script标签引入了.js的文件,则在浏览器地址栏呈现的地址类似是
这样会出现跨域问题。
解决方案:
1、本地搭建一个服务器去进行资源的访问
const http = require('http')
const fs = require('fs')
const path = require('path')
const obj = {
".png": "image/png",
".jpg": "image/jpg",
".html": "text/html;charset=utf8",
".js": "application/javascript;charset=utf8",
".css": "text/css;charset=utf8"
}
const server = http.createServer(function (req, res) {
console.log(req.url)
let filePath
if (req.url === '/' || req.url === '/index.html') {
filePath = path.join(__dirname, 'index.html')
} else {
filePath = path.join(__dirname, req.url)
}
fs.readFile(filePath, (err, data) => {
if (err) {
res.setHeader('Content-Type', 'text/html; charset=utf-8')
res.write('<h1>404错误</h1><p>你要找的页面不存在</p>')
res.end()
} else {
const extName = path.extname(filePath)
console.log(extName)
switch (extName) { // 不同文件返回不同类型
case ".html":
res.writeHead(200, {
"Content-Type": "text/html"
})
break
case ".js":
res.writeHead(200, {
"Content-Type": "text/javascript"
})
break
case ".css":
res.writeHead(200, {
"Content-Type": "text/css"
})
break
case ".gif":
res.writeHead(200, {
"Content-Type": "image/gif"
})
break
case ".jpg":
res.writeHead(200, {
"Content-Type": "image/jpeg"
})
break
case ".png":
res.writeHead(200, {
"Content-Type": "image/png"
})
break
case ".json":
res.writeHead(200, {
"Content-Type": "text/plain"
})
break
default:
res.writeHead(200, {
"Content-Type": "application/octet-stream"
})
}
console.log('有人访问了你的服务器')
// res.setHeader('Content-Type', 'text/html; charset=utf-8')
res.end(data)
}
})
})
server.listen(8888, function () {
console.log('服务已成功启动')
})
2、本地搭建一个服务器去进行资源的访问
学习发现问题,解决问题记录
参考学习: