簡體   English   中英

從服務端向客戶端發送響應(Node.js、javascript)

[英]Send a response from the serve-side to client-side (Node.js, javascript)

基於下面的結構,我想將我的響應(簡單數組 ["Tom", "Bob", "Sam"])從 server.js 發送到 index.js 有可能嗎?

服務器.js

app.get("/*", (req, res) => {
    res.sendFile(path.resolve(__dirname, "frontend", "index.html"));
});

app.post('/settings', function(req, res, next){
res.status(200).json({
                ok: true,
                data: ["Tom", "Bob", "Sam"]
            }); 
});

app.listen(process.env.PORT || 3000);

前端/索引.html

    <nav class="nav">
        <a href="/">Dashboard</a>
        <a href="/settings">Settings</a>
    </nav>
    <div id="app"></div>
    <script type="module" src="/static/js/index.js"></script>

/frontend/static/js/index.js

document.querySelector("#app").innerHTML = await view.getHtml(); // load page.html
//console.log(data);

/frontend/static/html/page.html

        <button id="btn">Save</button>
       <script>
     
   var btn = document.getElementById("btn");
btn.addEventListener("click", function() {

  fetch('/settings', {
    method: 'POST', 
           headers: {
            "Content-Type": "text/plain"
        },
    body: JSON.stringify(anotherData), 
    headers: {
      'Content-Type': 'application/json'
    }
  }).then(response => response.json())
    .then(function(response) {
        if (response.ok) {
            console.log('got data: ', response.data);
        }
    }).catch(function(error) {
        console.log(error);
    });
  

}, false);
   </script>

感謝您的評論 - 我相信我明白您現在的要求。

如果您想檢索 index.js 文件中的數據,處理此問題的最佳方法可能是將您的請求代碼移動到 index.js。 從您的 page.html 文件中刪除標簽,然后將其放在 index.js 中。 index.js 中的代碼將在頁面加載后運行,類似於頁面腳本中發生的情況。

您需要等到您的 fetch 完成后再對結果數據執行任何操作,但是如果您將 fetch 移動到 index.js 中,您可以使用數據調用文件中的其他函數,或者在您的 fetch 之外聲明一個變量調用以讓 index.js 中的其他函數使用它。

暫無
暫無

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

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