簡體   English   中英

在前端使用 fetch 從 express.js 服務器獲取響應

[英]Get response from express.js server using fetch on frontend

我正在學習 javascript 並表達。 我已經制作了可以正常工作的后端應用程序,但我不知道如何從瀏覽器發送請求並從服務器接收響應 這是我嘗試過的一個簡單示例:

服務器.js

const express = require("express");
const app = express();

app.listen(3000, () => {
  console.log("Listening on port 3000!")
})

app.get("/", (req, res) => {
  res.send("Hello");
})

服務器在glitch.com平台上。 當我從瀏覽器 go 到https://expressjs-test.glitch.me/項目時,我在 HTML 文檔中看到Hello消息(它工作正常)。

從我的瀏覽器執行的 Javascript 文件

let req = fetch("https://expressjs-test.glitch.me/");
req.then(response => console.log(response));

當我嘗試這樣做時遇到的問題是

Access to fetch at 'https://expressjs-test.glitch.me/' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

我在 stackoverflow 和其他網站上看到了其他問題,但不明白如何修復這個 cors 錯誤。

感謝您的時間。 對不起,如果我在這篇文章中犯了錯誤。

當您在glitch.com上托管應用程序時,您需要允許訪問域,即哪個域可以訪問您的后端。 完成此操作后,您將能夠從 API 接收數據。

也可以暫時添加chrome cors插件並啟用。 啟用后,重新加載 web 頁面,您將能夠看到響應。

另一種測試或從 API 獲取數據的方法,您可以使用PostMan或者如果使用 Visual Studio 代碼,您可以使用來自市場的迅雷客戶端。

如果控制台中有設置,我建議您將 cors 添加到您的 Node.js 服務器。

const express = require("express"), 
      app = express(),  
      cors = require("cors"), // importing the `cors` package

const whitelist = ['http://example1.com', 'http://example2.com']
const corsOptions = {
  origin: function (origin, callback) {
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  }
}

app.use(cors(corsOptions)) // tells Express to use `cors`, and solves the issue

app.listen(3000, () => {
  console.log("Listening on port 3000!")
})

app.get("/", (req, res) => {
  res.send("Hello");
})


您應該在此處查看cors文檔,並且還有關於故障 cors 問題的另一個鏈接。

您需要在您的應用程序中使用cors 由於域不同,因此可以從前端應用程序訪問它。

const cors = require('cors');

這允許您允許任何前端域

app.use(cors({
    origin: '*'
}));

這使您可以允許某些

app.use(cors({
    origin: ['https://siteA.com', 'https://siteB.com']
}));

暫無
暫無

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

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