簡體   English   中英

HTML 到 Node.js 服務器 POST 請求在 localhost 上使用 Fetch

[英]HTML to Node.js server POST request on localhost with Fetch

請原諒任何錯誤使用的術語或單詞,仍在嘗試理解 Node.js。

我在同一台 PC 上運行帶有 LiveServer 和 Node.js 服務器的網站。 我意識到我可以將網站作為 Node.js 應用程序運行,但我正在嘗試使用 POST 和 Fetch 將文件從網站發送到服務器。

服務器將處理文件復制,也許還有一些我覺得有趣的事情,但現在就是這樣。

問題是我什至無法連接到本地主機。 LiveServer 在端口 5501 上運行,Node 服務器在端口 5000 上運行。

下面是網站的 index.js 文件的代碼,它只需要一個拖放事件並嘗試將文件發送到 localhost:5000:

                var file = event.dataTransfer.items[i].getAsFile();
                console.log('... file[' + i + '].name = ' + file.name);

                var data = new FormData();
                data.append('file', file);

                const url = new URL('http://localhost:5000/');

                fetch(url, {
                    method:'POST',
                    body: data
                })
            }

這是 Node.js 服務器代碼:

const express = require('express'); //Import the express dependency
const cors = require('cors');

const app = express();              //Instantiate an express app, the main work horse of this server
const port = 5000;                  //Save the port number where your server will be listening

//setting middleware
app.use('/dist', express.static('dist'));

app.use(cors({
    allowedOrigins: [
        'http://localhost:5000'
    ]
}));

// //Idiomatic expression in express to route and respond to a client request
// app.get('/', (req, res) => {        //get requests to the root ("/") will route here
//     res.sendFile('src/index.html', { root: __dirname });      //server responds by sending the index.html file to the client's browser
//     //the .sendFile method needs the absolute path to the file, see: https://expressjs.com/en/4x/api.html#res.sendFile 
// });


app.listen(port, () => {            //server starts listening for any attempts from a client to connect at port: {port}
    console.log(`Now listening on port ${port}`);
});


app.post('http://localhost:5000/', function (req, res) {
    // const body = req.body.Body
    // res.set('Content-Type', 'text/plain')
    // res.send(`You sent: ${body} to Express`)
    res.sendFile('src/index.html', { root: __dirname });      //server responds by sending the index.html file to the client's browser

})

我在 Chrome 中遇到的錯誤是:POST http://localhost:5000/404(未找到)

我想要做的甚至可能嗎? 我嘗試了輸入 URL 的不同變體,但仍然收到相同的錯誤消息。 谷歌也沒有幫助。

任何幫助表示贊賞,在此先感謝。

app.METHOD 的第一個參數必須是調用中間件 function 的路徑; 可以是以下任何一種:

  1. 表示路徑的字符串。
  2. 路徑模式。
  3. 匹配路徑的正則表達式模式。
  4. 以上任何一種組合的數組。

所以因此這條線

app.post('http://localhost:5000/', ...)

必須只是一個路徑名,所以用這個替換它

app.post('/', ... )

暫無
暫無

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

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