hprose / hprose-golang

Hprose is a cross-language RPC. This project is Hprose for Golang.
MIT License
1.26k stars 205 forks source link

在golang做server,用js调用遇到跨域问题怎么解决? #93

Closed shioyim closed 5 years ago

shioyim commented 5 years ago

先贴出主要代码 //server type event struct{}

func (e event) OnSendHeader(ctx rpc.HTTPContext) { ctx.Response.Header().Set("Access-Control-Allow-Origin", "http://127.0.0.1:8081"); ctx.Response.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE"); ctx.Response.Header().Set("Access-Control-Allow-Headers","Authorization") }

func Server() { service := rpc.NewHTTPService() handler := struct { User user }{} service.Event = event{} ……

//client …… export function UserGet() { return (dispatch, getState) => { const cluster = localStorage.getItem('cluster'); const token = localStorage.getItem('token'); dispatch(userGetRequest()); if (!cluster || !token) { dispatch(userGetFailure('No authorization')); return; } const client = Client.create(${cluster}/api, { User: ['Get'] });

client.setHeader('Authorization', `Bearer ${token}`);
client.User.Get(null, (resp) => {
  if (resp.success) {
    dispatch(userGetSuccess(resp.data));
  } else {
    dispatch(userGetFailure(resp.message));
  }
}, (resp, err) => {
  dispatch(userGetFailure('Server error'));
  console.log('【Hprose】User.Get Error:', resp, err);
});

}; } ……

版本: server:golang1.12 hprose 2.0 client :hprosejs 2.0.33

    我用firefox调用时提示 missing token ‘authorization’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel),

用chrome调用时提示 Access to XMLHttpRequest at 'http://127.0.0.1:9876/api' from origin 'http://127.0.0.1:8081' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response. 请问问题到底出现在哪?我是不是哪里写错了?貌似onSendHeader没有起到作用,求解决。

andot commented 5 years ago

hprose 自带跨域支持,不要自己加什么 Header。

shioyim commented 5 years ago

虽然自带跨域支持但是我还是需要保留"Access-Control-Allow-Headers","Authorization"。我在service.Event定义了OnSendHeader,并且添加了这一句,但是并没有执行,问题就出现在这里。您能帮我看下如何解决这个问题?

andot commented 5 years ago

如果没执行说明你设置的 event 并没有实现接口 sendHeaderEvent 或 sendHeaderEvent2。

注意指针和引用不要少。

shioyim commented 5 years ago

指针我不熟悉,改过后还是没有执行,我把改过的代码给您看下,麻烦您看下哪里写的不对。谢谢了 type sendHeaderEvent2 struct{} func (e *sendHeaderEvent2) OnSendHeader(ctx rpc.HTTPContext) { ctx.Response.Header().Set("Access-Control-Allow-Headers","Authorization") } service := rpc.NewHTTPService() service.Event = &sendHeaderEvent2{} ...

shioyim commented 5 years ago

或者您给个自定义响应头的实例让我参考好吗?我就差这一点就做好了

andot commented 5 years ago
type sendHeaderEvent interface {
    OnSendHeader(context *HTTPContext)
}

type sendHeaderEvent2 interface {
    OnSendHeader(context *HTTPContext) error
}

这两个接口的定义是这样的。

不是你熟悉不熟悉指针的问题,是你少了 * 的问题。

shioyim commented 5 years ago

完美解决,十分感谢