gSOAP specify Access-Control-Allow-Origin

gSOAP specify Access-Control-Allow-Origin

本文关键字:Access-Control-Allow-Origin specify gSOAP      更新时间:2023-10-16

我已经用gSOAP开发了webservice。其中一个方法返回json输出。然而,浏览器需要传递标头(Access-Control-Allow-Origin)。gSOAP是否支持在发送数据之前传递报头?

乌利希期刊指南:

解决方案。只需在http_response函数中添加一些代码:

static int
http_response(struct soap *soap, int status, size_t count)
{
 /* some code goes here*/
if ((err = soap->fposthdr(soap, "Access-Control-Allow-Origin", "*")))
      return err;
  if ((err = soap->fposthdr(soap, "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, CONNECT")))
      return err;
  if ((err = soap->fposthdr(soap, "Access-Control-Allow-Headers", "X-Requested-With, Content-Type")))
      return err;
  if ((err = soap->fposthdr(soap, "Access-Control-Allow-Credentials", "true")))
      return err;
 /* some code goes here*/
}

我从来没有找到任何方法在我自己的代码中做到这一点-但我能够通过修改stdsoap2.cpp来做到这一点,因为您需要将其编译到您的代码中。我所做的是在http_post函数结束之前添加ClientCertSubjectDN头:

/******************************************************************************/
#ifndef WITH_NOHTTP
#ifndef PALM_1
static int
http_post(struct soap *soap, const char *endpoint, const char *host, int port, const char *path, const char *action, size_t count)
{ register const char *s;
  register int err;
  ... the code of the function (except the return at the end) ...
  /* add more headers */
  if ((err = soap->fposthdr(soap, "ClientCertSubjectDN", "CN=IVR Production")))
    return err;
  return soap->fposthdr(soap, NULL, NULL);
}
#endif
#endif

实际上有一种不需要更改gsoap代码就可以将自己的HTTP头添加到服务器响应中的方法。

  1. 定义一个变量来存储原始回调钩子fposthdr的地址
  2. 定义你自己的实现fposthdr
  3. 函数fposthdr在上述变量中的存储地址
  4. 设置你自己的实现fposthdr
  5. 在你自己的fposthdr实现中使用fposthdr的原始实现来发出HTTP头文件

代码示例:

...
/* Declaration of own implementation of fposthdr */
int my_fposthdr(struct soap *soap, const char *key, const char *val);
/* Definition of variable to store address of original fposthdr */
int (*org_fposthdr) (struct soap *soap, const char *key, const char *val) = NULL;
...
struct soap *soap
...
/* Store address of original function and set own implementation */
org_fposthdr = soap->fposthdr;
soap->fposthdr = my_fposthdr;
...
int my_fposthdr(struct soap *soap, const char *key, const char *val) {
    int res;
    if (key == NULL) {
        res = org_fposthdr (soap, "Access-Control-Allow-Origin", "*");
        ...
    }
    /* Make sure to finally call original fposthdr with key and value being NULL pointers. */
    return org_fposthdr (soap, key, val);
}
...
评论>:上面的示例实现my_fposthdr在gsoap发出的所有"默认"HTTP头之后发出额外的HTTP头。回调钩子由gsoap在每个header调用一次,并在keyval作为NULL指针时再次调用。因此,您可以让您的代码检测这些NULL指针并发出您自己的头文件。最后,你必须调用原始的fposthdr, val为NULL指针,否则没有HTTP有效载荷,即SOAP响应将被发送。