最佳答案
我创建了旅行服务器。它工作得很好,我们可以通过 Insomnia 发出 POST
请求,但是当我们通过前端的 Axios 发出 POST
请求时,它会发送一个错误:
has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.
我们对公理的要求是:
let config = {
headers: {
"Content-Type": "application/json",
'Access-Control-Allow-Origin': '*',
}
}
let data = {
"id": 4
}
axios.post('http://196.121.147.69:9777/twirp/route.FRoute/GetLists', data, config)
.then((res) => {
console.log(res)
})
.catch((err) => {
console.log(err)
});
}
我的行动文件:
func setupResponse(w *http.ResponseWriter, req *http.Request) {
(*w).Header().Set("Access-Control-Allow-Origin", "*")
(*w).Header().Set("Access-Control-Allow-Methods", "POST,GET,OPTIONS, PUT, DELETE")
(*w).Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}
func WithUserAgent(base http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
ua := r.Header.Get("Jwt")
ctx = context.WithValue(ctx, "jwt", ua)
r = r.WithContext(ctx)
setupResponse(&w, r)
base.ServeHTTP(w, r)
})
}
const (
host = "localhost"
port = 5432
user = "postgres"
password = "postgres"
dbname = "postgres"
)
func main() {
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
"password=%s dbname=%s sslmode=disable",
host, port, user, password, dbname)
server := &s.Server{psqlInfo}
twirpHandler := p.NewFinanceServiceServer(server, nil)
wrap := WithUserAgent(twirpHandler)
log.Fatalln(http.ListenAndServe(":9707", wrap))
}
正如我之前在 Insomnia 上所说,它工作得很好,但是当我们提出一个 Axios POST
请求时,浏览器控制台上会出现以下内容:
已被 CORS 策略阻塞: 对飞行前请求的响应没有通过访问控制检查: 它没有 HTTP OK 状态。