微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

提取API无法加载file:/// C:/ Users / Jack / Desktop / Books_H / book-site / public / api / booksURL方案必须为“ http”或“ https”才能进行CORS请求

如何解决提取API无法加载file:/// C:/ Users / Jack / Desktop / Books_H / book-site / public / api / booksURL方案必须为“ http”或“ https”才能进行CORS请求

好吧,这是我必须做的,如果它将来对所有人都有所帮助。这些都是基本的东西,但是我是初学者,所以我们开始吧。打开命令提示符。转到项目的目标位置(index.js文件所在的位置)并编写:

$ npm init -y
$ npm install -g express-generator
$ npm install express -S
$ npm install connect -S
$ npm install serve-static -S

然后转到server.js文件的目标并编写

$ node server.js

之后,我可以在浏览器中运行我的页面,在URL中键入http:// localhost:8080 /

解决方法

刚开始在我的学校学习node
js。他们给我们完成了一半任务,我需要使next和prev按钮起作用。但是,当我运行index.html时,控制台中会出现一些错误。错误是:

“获取API无法加载文件:/// C:/Users/Jack/Desktop/Books_H/book-
site/public/api/books。URL方案必须为“ http”或“ https”才能进行CORS请求。”

另一个是:

“未捕获(承诺)TypeError:无法在HTMLDocument.document.addEventListener处获取”。

我什至不知道如何开始解决这个问题。有什么帮助吗?

    <!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>

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文件

    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",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",res) => {
    fs.readFile("data/books.json",err);
            return;
        }

        let books = JSON.parse(data);
        let titles = books.map(book => book.title);
        res.send(JSON.stringify(titles));
    });
})

apiRouter.get("/books/author",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.
*/

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。