【问题标题】:net::ERR_CONNECTION_REFUSED Slim Frameworknet::ERR_CONNECTION_REFUSED 超薄框架
【发布时间】:2018-07-31 23:13:06
【问题描述】:

就是这样。我在服务器上运行我的 API,它在服务器的 localhost:8080 中运行。 有人告诉我,为了从我的机器(使用 vpn)从本地访问 api,url 是 xxx.xxx.xxx:8080 所以我尝试了

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

而我的api路由是这样的

$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;
   ....

但我从 chrome 收到此错误

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

知道会是什么吗?我是否需要将设置更改为我的 Slim 配置或其他内容?

【问题讨论】:

    标签: php angularjs slim


    【解决方案1】:

    这是一个所谓的:CORSPreflight request

    您可以尝试添加这个小型中间件以允许所有预检请求。当然,您应该添加自己的安全逻辑。

    // 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;
    });
    

    【讨论】:

    • 我只需要稍微改变一下,这对我有用。 $app->options('/{routes:.+}', function ($request, $response, $args) { return $response; }); $app->add(function ($req, $res, $next) { $response = $next($req, $res); return $response ->withHeader('Access-Control-Allow-Origin', '* ') ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization, token') ->withHeader('Access-Control-Allow-Methods', 'GET、POST、PUT、DELETE、OPTIONS'); });
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-11
    • 1970-01-01
    相关资源
    最近更新 更多