我有一個在NodeJS服務器上運行的ReactJS應用,使用Express是因為我需要同步前后端路由器。 我還使用了一個使用Chi的Go API,它作業得很好(我已經用postman做了測驗,它確實在作業)。 為了從 ReactJS 向我的 Go API 發送請求,我使用了 Axios,但我的控制臺中出現了一個錯誤:
訪問 XMLHabital 的請求。
從原點'http://localhost:3000'訪問'http://localhost:8080/api/connection/getToken'的 XMLHttpRequest 已被 CORS 策略阻止。對preflight請求的回應沒有通過訪問控制檢查。所請求的資源上沒有 "訪問控制-允許-起源 "頭。
但是我已經對我的 Axios 請求和我的 Golang API 代碼進行了一些修改。
以下是我的 ReactJS Axios 請求:
axios.defaults.headers。 post['Content-Type'] ='application/x-www-form-urlencoded';
axios.get('http://localhost:8080/api/connection/getToken'/span>, {
headers: {
'Access-Control-Allow-Origin': true,
code: 代碼。
}
}).then(res => console.log(res) )。
下面是我的Go代碼:
func connectInit(w http.ResponseWriter, r *http.Request){
w.Header().Set("Access-Control-Allow-Origin"/span>, "*"/span>)
if r.Header.Values("code") != nil {
code := r.Header.Get("code")
clientToken, err := getClientToken(code)
if err != nil {
fmt.Fprint(w, err.Error())
}
fmt.Fprint(w, clientToken)
}
}
下面是我在Go中使用的Chi路由器:
func ConnexionRoutes() *chi。 Mux {
router := chi.NewRouter()
router.Get("/getToken"/span>, connectInit)
return router
}
謝謝你!
uj5u.com熱心網友回復:
你遇到的問題是,go服務器是在原點提供服務的 http://localhost:8080
而 react 本地 webapp 當然是在原點 http://localhost:3000(這是我大部分時間的情況)
根據https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin,原點(就瀏覽器而言)是:
<方案> "://" <主機名> [ ":" <埠> ]
瀏覽器檢測到JS react網路應用程式正試圖訪問另一個沒有特定頭的來源(8080埠),因此將其阻止。
對此的一個解決方案是配置 go API,使其回傳適當的頭資訊 Access-Control-Allow-Origin。*。
甚至更好的是,我個人使用的是:
。import "github.com/go-chi/cors"
router := chi.NewRouter()
router.Use(cors.AllowAll().Handler)
更多關于CORS的資訊請點擊這里。https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/310208.html
標籤:
上一篇:Heroku使用ReactJS消費API時,請求的資源上沒有'Access-Control-Allow-Origin'頭。
