两个页面具有相同的协议(protocol),主机(host)和端口号(port)才是同源(即指在同一个域),当一个请求url的协议、域名、端口三者之间任意一个与当前页面url不同即为跨域
当出现跨域时:
【1】无法读取非同源网页的 Cookie、LocalStorage 和 IndexedDB
【2】无法接触非同源网页的 DOM
【3】无法向非同源地址发送 AJAX 请求
本地环境使用document.domain和window.location.host获取一些域名端口之类的信息都是空,请求文件总是会遇到跨域问题,Node.js 是一个开源和跨平台的 JavaScript 运行时环境,于是尝试在node服务器上运行页面
安装node
初始化 执行 npm init 生成package.json
npm init
方法一:
1.安装express
npm i express -S
2.新建一个server.js并运行 node server.js
server.js
const hostname = '127.0.0.1'
const port = 7777
const express = require('express');
const fs = require("fs");
const app = express();
// 在 Node.js 中读取文件最简单的方式是使用 fs.readFile() 方法,向其传入文件路径、编码、以及会带上文件数据(以及错误)进行调用的回调函数
// 使用fs.readFile打开html文件
app.get("/test.html", (request, response) => {
fs.readFile("./" + request.path.substr(1), (err, data) => {
// body
if (err) {
console.log(err);
//404:NOT FOUND
response.writeHead(404, { "Content-Type": "text/html" });
}
else {
//200:OK
response.writeHead(200, { "Content-Type": "text/html" });
response.write(data.toString());
}
response.end();
});
});
app.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`)
})
3.打开http://127.0.0.1:7777/test.html
方法二:
1.安装live-server
cnpm i live-server -S
2.修改package.json配置
在script项中添加
"dev": "./node_modules/.bin/live-server --port=7777"
3.命令行中执行npm run dev