英文:
ReactJS, Golang server CORS content-type trouble
问题
你好!根据你提供的信息,你遇到了CORS(跨域资源共享)的问题。这个错误是由于浏览器的安全策略导致的,它阻止了从一个源(origin)向另一个源发送跨域请求。
在你的代码中,你已经尝试在服务器和客户端上多次更改头部信息,但是没有成功。这可能是因为你的服务器没有正确配置CORS。
在你的服务器代码中,你已经设置了Access-Control-Allow-Origin
头部为*
,这允许来自任何源的请求。但是,你还需要设置Access-Control-Allow-Headers
头部,以允许Content-Type
字段在预检请求的响应中。
你可以尝试在服务器代码中添加以下行来设置Access-Control-Allow-Headers
头部:
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
这样做后,重新运行服务器代码并尝试再次发送POST请求,看看问题是否解决了。
希望这可以帮助到你!如果还有其他问题,请随时提问。
英文:
So I've been trying to connect my reactJS local client to my Golang local server with a POST request, but I keep getting this error:
> Access to fetch at 'http://localhost:8080/' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
I've already tried to change the heathers on the server and client side multiple times, but I've got no luck so far. FYI everything works just fine in Postman.
This is my code on client side
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
First: this.state.first,
Second: this.state.second,
Symbol: this.state.symbol,
Date: this.state.date,
})
};
fetch('http://localhost:8080/', requestOptions)
.then(response => { return response.json() })
.then(data => {
this.setState({ result: data });
})
.catch(console.log)
}
and this is it on the server side
type Params struct {
First string
Second string
Symbol string
Date string
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
fmt.Fprintf(w, "Hi there")
return
}
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "application/json")
var params Params
err := json.NewDecoder(r.Body).Decode(&params)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "%v", err)
return
}
// somthing else here
})
what am I doing wrong?
答案1
得分: 1
最后,我缺少一个头部信息。
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
感谢 @mkopriva!
英文:
In the end, I was missing a header.
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
credit goes to @mkopriva!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论