Javascript Fetch API 无法加载 file:///C:/Users/Jack/Desktop/Books_H/book-site/public/api/books。对于 CORS 请求,URL 方案必须是“http”或“https”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48728334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fetch API cannot load file:///C:/Users/Hyman/Desktop/Books_H/book-site/public/api/books. URL scheme must be "http" or "https" for CORS request
提问by Happy Coconut
Just started learning node js in my school. They gave us this half-finished task and i need to make the next and prev buttons work. However i get some errors in the console the moment i run the index.html. The errors are:
刚开始在我学校学习 node js。他们给了我们这个半完成的任务,我需要让下一个和上一个按钮工作。但是,当我运行 index.html 时,控制台中出现了一些错误。错误是:
"Fetch API cannot load file:///C:/Users/Hyman/Desktop/Books_H/book-site/public/api/books. URL scheme must be "http" or "https" for CORS request."
“Fetch API 无法加载 file:///C:/Users/Hyman/Desktop/Books_H/book-site/public/api/books。对于 CORS 请求,URL 方案必须是“http”或“https”。”
and the other one is :
另一个是:
"Uncaught (in promise) TypeError: Failed to fetch at HTMLDocument.document.addEventListener".
“未捕获(承诺)类型错误:无法在 HTMLDocument.document.addEventListener 处获取”。
I dont even know how to start to solve this problem. Any help?
我什至不知道如何开始解决这个问题。有什么帮助吗?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=1000, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Hello</title>
</head>
<body>
Hello from the other side! <b>Total: <span id="total"></span></b><br/>
<button id="author">Sort by author</button>
<button id="title">Sort by title</button>
<table id="books" border="1">
<tr>
<th>
Author
</th>
<th>
Book Title
</th>
</tr>
</table>
<script src="index.js"></script>
</body>
</html>
The java script file
java脚本文件
document.addEventListener("DOMContentLoaded", () => {
processResponse(fetch("api/books"));
document.getElementById("author").addEventListener("click", () =>{
processResponse(fetch("api/books?sortby=author"))
});
document.getElementById("title").addEventListener("click", () =>{
processResponse(fetch("api/books?sortby=title"))
});
});
function processResponse(response) {
let table = document.getElementById("books");
let total = document.getElementById("total");
response.then(data => data.json())
.then(value => {
table.innerHTML = "";
const tr = document.createElement("tr");
let th = document.createElement("th");
th.innerHTML = "Author";
tr.appendChild(th);
th = document.createElement("th");
th.innerHTML = "Book Title";
tr.appendChild(th);
table.appendChild(tr);
for (let index = 0; index < value.books.length; index++) {
const book = value.books[index];
const tr = document.createElement("tr");
let td = document.createElement("td");
td.innerHTML = book.author;
tr.appendChild(td);
td = document.createElement("td");
td.innerHTML = book.title;
tr.appendChild(td);
table.appendChild(tr);
}
total.innerHTML = value.total;
});
}
server.js file
server.js 文件
const fs = require('fs');
const express = require('express');
const app = express();
app.use(express.static("public"));
app.get("/", (req, res) => {
res.sendFile("index.html", { root: __dirname + "/public" });
});
const apiRouter = express.Router();
apiRouter.get("/books", (req, res) => {
let sortOrder = req.query["sortby"];
fs.readFile("data/books.json", { encoding: 'utf8' }, (err, data) => {
if (err) {
console.error("ERROR is: ", err);
return;
}
let books = JSON.parse(data);
if (sortOrder === "author") {
books.sort((a, b)=> a.author.localeCompare(b.author));
} else if (sortOrder === "title") {
books.sort((a, b)=> a.title.localeCompare(b.title));
}
res.send(JSON.stringify({
books: books.slice(0, 50),
total: books.length
}));
});
})
apiRouter.get("/books/title", (req, res) => {
fs.readFile("data/books.json", { encoding: 'utf8' }, (err, data) => {
if (err) {
console.error("ERROR is: ", err);
return;
}
let books = JSON.parse(data);
let titles = books.map(book => book.title);
res.send(JSON.stringify(titles));
});
})
apiRouter.get("/books/author", (req, res) => {
fs.readFile("data/books.json", { encoding: 'utf8' }, (err, data) => {
if (err) {
console.error("ERROR is: ", err);
return;
}
let books = JSON.parse(data);
let authors = books.map(book => book.author);
res.send(JSON.stringify(authors));
});
})
app.use("/api", apiRouter);
app.listen(8080, () => console.log('Example app listening on port 8080!'));
/*
And the books.json file that i guess you dont need so i wont post it.
My folder structure is:
Books > data Folder > books.json.
Books > public Folder > index.html.
Books > public Folder > index.js.
Books > server.js.
*/
回答by Happy Coconut
Well this is what i had to do if it helps anyone in the future at all. This is all basic stuff but i am beginner so here we go. Open command prompt. Go to the destination of your project( where the index.js file is ) and write:
好吧,如果它对将来的任何人有帮助,这就是我必须做的。这是所有基本的东西,但我是初学者,所以我们开始吧。打开命令提示符。转到项目的目的地(index.js 文件所在的位置)并写入:
$ npm init -y
$ npm install -g express-generator
$ npm install express -S
$ npm install connect -S
$ npm install serve-static -S
then go to the destination of your server.js file and write
然后转到 server.js 文件的目的地并写入
$ node server.js
After this i could run my page in browser typing http://localhost:8080/in the URL.
在此之后,我可以在浏览器中运行我的页面,在 URL 中输入http://localhost:8080/。
回答by Serge
If you are under Windows, create a new site in your local IIS (you should enable IIS in Windows components if not already) to your project folder. Then open http://localhost:8080(or other port you can setup in the ISS for your new site)
如果您使用的是 Windows,请在您的本地 IIS 中创建一个新站点(如果尚未启用,则应在 Windows 组件中启用 IIS)到您的项目文件夹。然后打开http://localhost:8080(或您可以在 ISS 中为您的新站点设置的其他端口)
回答by David Furlong
Add to script tag type='text/javascript'
添加到脚本标签 type='text/javascript'

