簡體   English   中英

如何通過本地客戶端和服務器的fetch API發出POST請求?

[英]How to make POST request via fetch API with local client and server?

我通過webpack和express運行兩個獨立的服務器; 開發服務器和客戶端服務器

我在客戶端上有一個按鈕,我想在按鈕點擊時向服務器發送POST請求。 我使用https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch中的示例創建請求

const testButton = document.querySelector(`button.test`);

const sendRequest = event => {
    event.preventDefault(); //stop or prevents the browser from executing the default action

    postData(`http://localhost:8080/`, { answer: 42 }) // line:32
        .then(data => console.log(JSON.stringify(data))) // JSON-string from `response.json()` call , line:33
        .catch(error => console.error(error));

    function postData(url = ``, data = {}) {
        // Default options are marked with *
        return fetch(url, { // line:38
            method: 'POST', // *GET, POST, PUT, DELETE, etc.
            mode: 'no-cors', // no-cors, cors, *same-origin
            cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
            credentials: 'same-origin', // include, *same-origin, omit
            headers: {
                'Content-Type': 'application/json',
                // "Content-Type": "application/x-www-form-urlencoded",
            },
            redirect: 'follow', // manual, *follow, error
            referrer: 'no-referrer', // no-referrer, *client
            body: JSON.stringify(data), // body data type must match "Content-Type" header
        });
        // .then(response => response.json()); // parses JSON response into native Javascript objects
    }

    console.log(`sends POST request from here`);
};
testButton.addEventListener(`click`, sendRequest);

當我點擊按鈕時,我收到此錯誤:

sends POST request from here // console.log message in request
POST http://localhost:8080/ 404 (Not Found)
postData @ index.js:38
sendRequest @ index.js:32
index.js:33 {}

package.json中的腳本

    "scripts": {
        "start": "webpack",
        "dev-server": "nodemon bin/dev localhost 8080",
        "dev-client": "webpack-dev-server --port 3000"
    }

webpack.config.js中的devServer


    devServer: {
        historyApiFallback: true,
        hot: true,
        inline: true,

        host: 'localhost',
        port: 3000,
         proxy: {
          '/api/': 'http://localhost:8080',
          }
    },

我試過這個代理

proxy: {
          '^/api/*': {
            target: 'http://localhost:8080/api/',
            secure: false
          }
        }
  1. 你有沒有啟動快遞服務器?
  2. 您的快遞應用程序是否具有空端點映射(它也必須是POST映射)?
  3. 如果你使用的是docker(快遞),它會聽你的內部端口嗎?

您的請求代碼乍一看似乎很好。

暫無
暫無

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

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