簡體   English   中英

節點 JS - 單擊按鈕時從 index.html 訪問 JSON

[英]Node JS - Access JSON from index.html on button click

我對 Node JS 相當陌生,我正在嘗試創建一個服務器,當用戶導航到 http://localhost:8000/ 時,它們會被路由到 index.html。 在那個 index.html 文件中會有一個按鈕,他們可以點擊獲取 JSON 數據。 這個 JSON 數據被下載到我自己的機器上,目的是托管在 Node JS 服務器上。 有 6 個 JSON 文件。

我的問題是,我可以在同一台服務器上托管 JSON 和 index.html 而不使用像 Express 這樣的框架嗎? 我有一個快遞解決方案,但如果可能的話,我想這樣做。

index.html -> 按下按鈕 -> 從服務器獲取 JSON(同一服務器?)

- - 編輯 - -

它適用於大學模塊,並獲得了概述的說明。 顯式節點。

您可以查看有關 static 文件的 express js。 例如:

app.use('/static', express.static('public'));

更多信息:

https://expressjs.com/pt-br/starter/static-files.html

我把收到的問題復雜化了。 我被告知只使用 http 和 fs 庫並訪問 JSON 之類的 localhost/8080/path/to/json。

為這個問題道歉。

設置環境

mkdir server
cd server
npm init
npm install express
touch server.js index.html
mkdir public

服務器.js

const express = require('express');
const app = express();
const path = require('path');

app.use('/public', express.static('public'));

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname + '/index.html'));
});

app.listen(80, () => console.log("Running on: http://localhost"));

索引.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Download JSON</title>
</head>
<body>
    <h1>Download</h1>
    <a href="public/sample.json" download="sample.json">Sample JSON</a>
</body>
</html>

將您的 JSON 放在公用文件夾結構中,並定期鏈接到它,就像上面的 HTML 示例一樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM