net::ERR_CONNECTION_REFUSED Slim Framework

馋奶兔 提交于 2019-12-11 07:31:48

问题


so this is it. I am running my API on a server, its running in localhost:8080 in the server. I was told that in order to access the api from locally from my machinne (using vpn) the url is xxx.xxx.xxx:8080 So i tried that

$http({
  url:'http://xxx.xxx.xxx.xxx:8080/login',
  method:"POST",
  data:{user:$scope.user, password:$scope.password}
})

and my api route is like this

$app->post('/login', function ($request, $response) {
  //Parametros que se pasan a la api
  $input  = $request->getParsedBody();
  $req = $input['usuario'];
  $md5pass = md5($input['password']);
  $sth = $this->db->prepare("query");
  //bindParam pasandole los parametros para evitar injecciones sql
  $sth->bindParam("password", md5($input['password']));
  $sth->bindParam("usuario", $input['usuario']);
  $sth->execute();
  $todos = $sth->fetchAll();
  $cliente_id = $todos->cliente_id;
   ....

but i get this error from chrome

OPTIONS http://xxx.xxx.xxx.xxx:8080/login net::ERR_CONNECTION_REFUSED

any idea what could it be? Do i need to change settings to my Slim configuration or something else?


回答1:


This is a so called: CORS Preflight request.

You can try to add this small middleware to allow all preflight requests. Of course, you should add your own security logic.

// CORS preflight middleware
$app->add(function (Request $request, Response $response, $next) {
    if ($request->getMethod() !== 'OPTIONS' || php_sapi_name() === 'cli') {
        return $next($request, $response);
    }

    $response = $next($request, $response);

    $response = $response->withHeader('Access-Control-Allow-Origin', '*');
    $response = $response->withHeader('Access-Control-Allow-Methods', $request->getHeaderLine('Access-Control-Request-Method'));
    $response = $response->withHeader('Access-Control-Allow-Headers', $request->getHeaderLine('Access-Control-Request-Headers'));

    return $response;
});


来源:https://stackoverflow.com/questions/48904780/neterr-connection-refused-slim-framework

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!