【发布时间】:2015-12-19 18:11:34
【问题描述】:
所以我正在尝试使用 isomorphic-fetch https://www.npmjs.com/package/isomorphic-fetch
我有一个用 go 编写的服务器,它返回 JSON 数据。这就是我打电话的方式-
export function fetchDistricts(geoState) {
return function (dispatch) {
dispatch(requestDistricts(geoState));
return fetch(`http://localhost:8100/districts/`)
.then(response => {console.log(response);})
.then(json => {
console.log("json");
});
}
我在 chrome 控制台中收到此错误
Fetch API cannot load http://localhost:8100/districts/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8200' is therefore not allowed access.
这很奇怪,因为在我的处理程序中我正在这样做
func getDistricts(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/jsonp;charset=UTF-8")
w.WriteHeader(http.StatusOK)
w.Header().Set("Access-Control-Allow-Origin", "*")
rows, err := db.Query("SELECT * from districts")
//other code here
此外,这是有效的
var activitiesDfD = $.ajax({
url: "http://localhost:8100/district/1/activities",
type: "GET",
dataType: "json"
});
$.when(activitiesDfD).then(function(data, textStatus, jqXhr) {
为什么在使用 fetch API 时会失败,我该如何解决这个问题?
编辑-
我已经试过了
func getDistricts(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/jsonp;charset=UTF-8")
w.Header().Set("Access-Control-Allow-Origin", r.Header.Get(`origin`))
w.WriteHeader(http.StatusOK)
结合以下两个建议 - 但错误是相同的。
【问题讨论】:
-
在您的 jQuery 示例中,您正在调用
localhost:81000,而在您的 fetch 示例中,您正在调用localhost:8100。这是问题中的拼写错误,还是您要查找的错误? -
这是一个错字 - 抱歉 - 正在更改
-
我不知道你的服务器是什么语言,但你打电话给
w.WriteHeader之前设置`Access-Control-Allow-Origin? -
语言是golang, err - 我是w.WriteHeader(http.StatusOK)
-
如果您重新排列它们以在
WriteHeader之前设置标题,它可能会起作用。实际上,您在写入套接字后在对象上设置标头,因此标头不会被发送。
标签: ajax go same-origin-policy