CORS在Symfony 2上错误地使用Javascript调用BeSimpleSOAPBundle

CORS on Symfony 2 errors BeSimpleSOAPBundle calling WebService with Javascript

本文关键字:Javascript 调用 BeSimpleSOAPBundle 错误 Symfony CORS      更新时间:2023-09-26

我正在使用BeSimpleSOAPBundle在symfony2上做我的web服务。我用SOA客户端扩展firefox测试我的web服务,我可以看到我的web服务没问题,但是当尝试用javascript测试时,这失败了。我从控制台浏览器

得到以下错误
OPTIONS http://192.168.0.68/controlid/web/app_dev.php/ws/loginOperador?wdls 405  (Method Not Allowed) jquery.js:4
OPTIONS http://192.168.0.68/controlid/web/app_dev.php/ws/loginOperador?wdls No   'Access-Control-Allow-Origin' header is present on the requested resource. Origin   'http://localhost' is therefore not allowed access. jquery.js:4
XMLHttpRequest cannot load    http://192.168.0.68/controlid/web/app_dev.php/ws/loginOperador?wdls. No 'Access-Control-   Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is    therefore not allowed access. (index):1
下面的代码是用javascript调用web服务的方式
function CallService()
{
    var webServiceURL = 'http://192.168.0.68/controlid/web/app_dev.php/ws/loginOperador?wdls';
    var soapMessage = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><goodbye xmlns="http://controlid/ws/loginOperador/1.0/"><name>'+$('#nombre').val()+'</name></goodbye></soap:Body></soap:Envelope>';
   jQuery.support.cors = true;
   //Llamamos a la función AJAX de JQuery
   $.ajax({
      type: "POST",
      url: webServiceURL,
      crossDomain : true,
      cache: false,
      data: soapMessage,
      processData: false,
      dataType: "xml",
      contentType: "application/soap+xml; charset=utf-8",
      success: OnSuccess,
      error: OnError
   });
   return false;
}

这是我在symfony上的web服务代码:

/**
  * Método que se encarga de verificar si un operador
  * puede tener acceso desde la aplicación móvil.
  *
  * @Soap'Method("login")
  * @Soap'Param("pin", phpType = "string")
  * @Soap'Result(phpType = "string")
*/
public function loginAction( $pin )
{
    $em =  $this->container->get('doctrine')->getEntityManager();       
    try 
    {
        $operador = $em->getRepository('controlidRondasBundle:Operador')->findOneBy(array('pin'=>$pin));
        if( empty($operador) )
        {
            return sprintf('Acceso denegado');
        }
        else{
            return sprintf('Bienvenido %s!', $operador->getNombre() );
        }
    } 
    catch ('Doctrine'Orm'NoResultException $e) 
    {
        return sprintf('Acceso denegado');
    }
}

这是我在symfony上的服务设置(app/conf/config.yml)

be_simple_soap: 
   services:
        DemoApi:
            namespace:     http://controlid/ws/DemoApi/1.0/
            binding:       rpc-literal
            resource:      "@controlidRondasBundle/Controller/RegisterController.php"
            resource_type: annotation
        loginOperador:
            namespace:     http://controlid/ws/loginOperador/1.0/
            binding:       rpc-literal
            resource:      "@controlidSeguridadBundle/Controller/OperatorSecurityController.php"
            resource_type: annotation

和routing_dev.yml:

_besimple_soap:
    resource: "@BeSimpleSoapBundle/Resources/config/routing/webservicecontroller.xml"
    prefix:   /ws

有人可以告诉我,我做错了什么?

我要做的是设置apache服务器

  1. 激活模块
a2enmod headers
service apache2 restart

2。编辑文件/etc/apache2/sites-enabled

<VirtualHost *:80>
 ....
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
...
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
...
    #The things that I added 
Header set Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, content-type"
Header always set Access-Control-Allow-Methods "POST, GET, PUT, DELETE, OPTIONS"
    #End of the thigns that I added 
</VirtualHost>

编辑

上面的答案只适用于本地主机,但是当我试图在主机或任何云上这样做时,错误仍然存在,所以答案是魔法包

安装:

php composer.phar require nelmio/cors-bundle:~1.0

然后加到project/app/AppKernel.php

public function registerBundles()
{
   $bundles = array(
    ...
    new Nelmio'CorsBundle'NelmioCorsBundle(),
    ...
   );
   ...
}

现在设置包和我在project/app/config/config.yml上的路径添加

nelmio_cors:
   defaults:
       allow_credentials: true
       allow_origin: []
       allow_headers: []
       allow_methods: []
       expose_headers: []
       max_age: 0
       hosts: []
   paths:
    '^/':
        allow_origin: ['*']
        allow_headers: ['origin', 'content-type']
        allow_methods: ['POST', 'PUT', 'GET', 'DELETE','OPTIONS']
        max_age: 3600

总结它的工作!!