因此,我一直试图通过POST请求将我的reactJS本地客户端连接到我的Golang本地服务器,但是我一直收到这样的错误:
访问从原点获取'http://localhost:8080/‘'http://localhost:3000’已被CORS策略阻止:在飞行前响应中,访问控制允许允许标头不允许请求标头字段内容类型。
我已经多次尝试更改服务器和客户端的heathers,但是到目前为止我没有运气。邮递员一切都很好。
这是我在客户端的代码
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)
}这是服务器端的
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(¶ms)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "%v", err)
return
}
// somthing else here
})我做错什么了?
发布于 2022-02-18 10:05:06
最后,我丢了一个头球。
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")信用归@mkopriva!
https://stackoverflow.com/questions/71171237
复制相似问题