ReactJS和Go API之间的请求

huangapple go评论97阅读模式
英文:

Requests between ReactJS Axios and Go API

问题

我有一个运行在NodeJS服务器上的ReactJS应用程序,使用Express框架,我使用它是因为我需要同步前端和后端的路由。
我还使用了一个使用Chi框架的Go API,它运行良好(我已经使用Postman进行了测试,它确实可以工作)。
为了从ReactJS向我的Go API发送请求,我使用了Axios,但是我在控制台中遇到了一个错误:

跨域资源共享(CORS)策略阻止了从源'http://localhost:3000'向'http://localhost:8080/api/connection/getToken'发送的XMLHttpRequest请求:响应预检请求未通过访问控制检查:所请求的资源上不存在'Access-Control-Allow-Origin'头。

但是我已经对我的Axios请求和Golang API代码进行了一些更改。

这是我的ReactJS Axios请求:

axios.defaults.headers.post['Content-Type'] ='application/x-www-form-urlencoded';
axios.get('http://localhost:8080/api/connection/getToken', {  
    headers: {
         'Access-Control-Allow-Origin': true,
         code: code,
        } 
}).then(res => console.log(res));

这是我的Go代码:

func connectInit(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Access-Control-Allow-Origin", "*")
    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", connectInit)
    return router
}

谢谢!

英文:

I have a ReactJS app running on a NodeJS server with Express that I used because I needed to sync my front and back routers.
I'm also using a Go API using Chi that works fine (I've done tests with postman and it is actually working).
To send requests to my Go API from ReactJS I use Axios but I have an error in my console:

Access to XMLHttpRequest at 'http://localhost:8080/api/connection/getToken' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

But I've already done some changes on both my Axios request and my Golang API code.

Here is my ReactJS Axios request:

    axios.defaults.headers.post['Content-Type'] ='application/x-www-form-urlencoded';
        axios.get('http://localhost:8080/api/connection/getToken', {  
            headers: {
                 'Access-Control-Allow-Origin': true,
                 code: code,
                } 
        }).then(res => console.log(res));

Here is my Go code:

    func connectInit(w http.ResponseWriter, r *http.Request) {
    	w.Header().Set("Access-Control-Allow-Origin", "*")
    	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)

    	}
    }

Here is my Chi router in Go:

    func ConnexionRoutes() *chi.Mux {
    	router := chi.NewRouter()
    	router.Get("/getToken", connectInit)
    	return router
    }

Thank you !

答案1

得分: 4

你遇到的问题是Go服务器的原始地址是http://localhost:8080,而React本地Web应用程序通常是在http://localhost:3000上提供的。

根据https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin中的说明,浏览器中的"origin"是指:

"://" [ ":" ]

浏览器检测到JS React Web应用程序试图访问另一个没有特定头部的来源(端口8080),因此阻止了该访问。

解决此问题的一种方法是配置Go API,使其返回适当的头部Access-Control-Allow-Origin: *

更好的方法是,对于chi,我个人使用以下代码:

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

英文:

the problem you have is that the go server is served on the origin http://localhost:8080

while the react local webapp is certainly served on the origin http://localhost:3000 (this is what I have most of the time)

According to https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin the origin (in the sense of the browser) is:

> <scheme> "://" <hostname> [ ":" <port> ]

the browser detects the JS react webapp is trying to access another origin (port 8080) that has no specific header and therefore blocking it.

One solution to this is to configure the go API so that it returns the appropriate header Access-Control-Allow-Origin: *.

Even better, for chi, I personnaly use:

import "github.com/go-chi/cors"

router := chi.NewRouter()
router.Use(cors.AllowAll().Handler)

More about CORS here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

答案2

得分: 0

React现在在package.json文件中提出了proxy字段,用于收集和重定向您的Web应用程序请求:

"proxy": "http://localhost:8080"

这样做应该可以解决跨域问题。

请参阅https://create-react-app.dev/docs/proxying-api-requests-in-development/。

英文:

React now proposes the proxy field in the package.json file to collect and redirect your webapp requests:

"proxy": "http://localhost:8080"

Should do the trick with no cors at all.

See https://create-react-app.dev/docs/proxying-api-requests-in-development/

huangapple
  • 本文由 发表于 2021年9月14日 03:42:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/69168256.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定