php - CORS JSON php 请求的资源上不存在 'Access-Control-Allow-Origin' header

标签 php angularjs json

我根本不知道如何解决这个问题,我已经坐在那里好几个小时了,什么也没有。 errors

从我的 Angular 来看,我使用 http.post 如下:

function PostReview(JSONObject) {
    if(JSONObject!=null){
         $http({ 
             url: 'http://localhost:8000/creation',
             method: "POST",
             data: JSONObject,
             headers: { "Content-Type":  "application/json"} });

         }
    }

在 php 中我尝试这样得到它:

public function created()
{
 $json = file_get_contents('php://input');
 $request = json_decode($json);
 var_dump($request);
// $email = $request->email;
//return response()->json($request);
}

我还有 Cors 类,我在其中处理了 OPTIONS 预检问题。我尝试在那里添加标题,但没有运气:

    class CorsMiddleware {
    protected $settings = [
                'origin' => '*',    // Wide Open!
                'allowMethods' => 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS',
                'allowHeaders' => 'Content-Type, Origin'];
    protected function setOrigin($req, $rsp)
    {
        $origin = $this->settings['origin'];
        if (is_callable($origin))
        {
            // Call origin callback with request origin
            $origin = call_user_func($origin, $req->header("Origin"));
        }
        $rsp->header('Access-Control-Allow-Origin', $origin);
    }

    protected function setExposeHeaders($req, $rsp)
    {
        if (isset($this->settings->exposeHeaders))
        {
            $exposeHeaders = $this->settings->exposeHeaders;

            if (is_array($exposeHeaders))
            $exposeHeaders = implode(", ", $exposeHeaders);

            $rsp->header('Access-Control-Expose-Headers', $exposeHeaders);
        }
    }
    protected function setMaxAge($req, $rsp)
    {
        if (isset($this->settings['maxAge']))
        $rsp->header('Access-Control-Max-Age', $this->settings['maxAge']);
    }

    protected function setAllowCredentials($req, $rsp)
    {
        if (isset($this->settings['allowCredentials']) && $this->settings['allowCredentials'] === True)
        $rsp->header('Access-Control-Allow-Credentials', 'true');
    }

    protected function setAllowMethods($req, $rsp)
    {
        if (isset($this->settings['allowMethods']))
        {
            $allowMethods = $this->settings['allowMethods'];

            if (is_array($allowMethods))
            $allowMethods = implode(", ", $allowMethods);

            $rsp->header('Access-Control-Allow-Methods', $allowMethods);
        }
    }
    protected function setAllowHeaders($req, $rsp)
    {
        if (isset($this->settings['allowHeaders']))
        {
            $allowHeaders = $this->settings['allowHeaders'];

            if (is_array($allowHeaders))
            $allowHeaders = implode(", ", $allowHeaders);

        }
        else // Otherwise, use request headers
        {
            $allowHeaders = $req->header("Access-Control-Request-Headers");
        }

        if (isset($allowHeaders))
        $rsp->header('Access-Control-Allow-Headers', $allowHeaders);

    }

    protected function setCorsHeaders($req, $rsp)
    {
        // http://www.html5rocks.com/static/images/cors_server_flowchart.png
        // Pre-flight
        if ($req->isMethod('OPTIONS'))
        {
            $this->setOrigin($req, $rsp);
            $this->setMaxAge($req, $rsp);
            $this->setAllowCredentials($req, $rsp);
            $this->setAllowMethods($req, $rsp);
            $this->setAllowHeaders($req, $rsp);
        }
        else
        {
            $this->setOrigin($req, $rsp);
            $this->setExposeHeaders($req, $rsp);
            $this->setAllowCredentials($req, $rsp);
        }
    }
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next) {

        if ($request->isMethod('OPTIONS')) {
            $response = new Response("", 200);
        }
        else {
            $response = $next($request);
        }

        $this->setCorsHeaders($request, $response);

        return $response;
    }

}

有人知道如何修复它吗?我尝试了多个示例,但没有任何效果适合我。


我认为在将 Angular 帖子方法更改为以下内容后我已经修复了它:

function PostReview(JSONObject) {
    if(JSONObject!=null){
         $http({ 
             url: 'http://localhost:8000/creation',
             method: "POST",
             data: JSONObject,
             headers: { "Content-Type": "application/x-www-form-urlencoded;charset=utf-8;", "Accept": "application/json"} });

         }
    }

现在我没有收到错误,方法是 post,但 postman 是空的。 enter image description here

最佳答案

您很可能没有正确设置响应 header 。您的屏幕截图表明 OPTIONS 回复中的 header 设置正确,但 POST 回复的 header 可能不同(且不足)。

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type, X-Requested-With');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT');
header('Access-Control-Max-Age: 600');

header() 必须在发送任何实际输出之前调用,无论是通过普通 HTML 标记、文件中的空行还是从 PHP。

但是,从您的 PHP 代码可以明显看出,您正在 API 框架的范围内工作,并且使用 header() 强制设置 header 可能不是最佳实践。

关于php - CORS JSON php 请求的资源上不存在 'Access-Control-Allow-Origin' header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44734734/

相关文章:

php - Wordpress - Woocommerce 删除 "Added to Cart"消息

php - 双重复 key 更新输入错误

javascript - 在另一个元素上对齐元素

javascript - 如何找到包含这些ID的数组元素?

android - Unity3d WWW 类在 android 上非常慢

php - 如何用 PDO::quote() 替换 mysql_escape_string

php - 执行代码时,用户 'root' @'localhost' MySQL 访问被拒绝 (Windows 7)

javascript - 突出显示来自不同标签的 Html 文档中的文本

javascript - 如何在 ng-repeat 中传递动态变量

JSON Schema 嵌套 If Then