Home>

Overview

We are currently developing applications of the following configuration.

React.js on the front end, LUMEN of the API server on the back end, and in the meantime, I have NGINX as a reverse proxy.
Therefore, we used CORS where you used AXIOS, a Promise based AJAX library from React.
I could set CORS on the LUMEN side and work around for a while, but if you go to a specific page, it will be played with CORS.
The screen transition uses React-Router. Personally, we believe that WebPack or NGINX settings are incorrect.
I checked variously in my own, but I do not solve ....
I would like to ask you to solve.

Content of Error

Access to XMLHTTPREQUEST AT 'HTTP: //LocalHost: 8000 /API /STICKY' FROM ORIGIN 'HTTP: //localhost: 3000' Has Been Blocked by Cors Policy: no 'Access-Control-Allow-Origin 'Header is Present on the Requested Resource.

Applicable code

//Nginx
server {
    Listen 0.0.0:80;
    server_name localhost;
    Charset UTF-8;
    # Root
    location /{
        root /var /www /Client /DIST;
        index index.html index.htm;
        try_files $ URI $ URI //DEX.HTML;
        Access_log /var/log/log/nginx/access.log;
        Error_log /var/log/nginx/error.log;
        IF ($ request_method= 'options') {
          add_header 'Access-Control-Allow-Origin: $ HTTP_ORIGIN');
          add_header 'Access-Control-Allow-Methods: get, post, delete, put, patch, options');
          add_header 'Access-Control-Allow-Credentials: TRUE');
          add_header 'Vary: Origin');
        }
        add_header 'Access-Control-allow-Origin' '$ HTTP_ORIGIN' ALWAYS;
        add_header 'Access-Control-Allow-Credentials' 'True' ALWAYS;
        add_header 'Access-Control-Allow-Methods' get, Post, Put, Patch, Delete, Options' Always;
        add_header 'Access-Control-Allow-Headers' 'ACCEPT, AUTHORIZATION, CACHE-CONTROL, CONTENT-TYPE, DNT, IF-MODIFIED-SINCE, KEEP-ALIVE, ORIGIN, USER-AGENT, X-Requested-with' Always;
    }
    # ReverseProxy: Lumen API Server
    LOCATION /API {
        Proxy_pass http://127.0.0.1: 8000;
        Access_log /var/log/log/nginx/access.log;
        Error_log /var/log/nginx/error.log;
        Location ~ \ .php $ {
            FASTCGI_PASS Server: 9000;
            fastcgi_index index.php;
            FastCGI_PARAM SCRIPT_FILENAME $ DOCUMENT_ROOT $ FASTCGI_SCRIPT_NAME;
            include FastCGi_Params;
        }
        IF ($ request_method= 'options') {
          add_header 'Access-Control-Allow-Origin: $ HTTP_ORIGIN');
          add_header 'Access-Control-Allow-Methods: get, post, delete, put, patch, options');
          add_header 'Access-Control-Allow-Credentials: TRUE');
          add_header 'Vary: Origin');
        }
        add_header 'Access-Control-allow-Origin' '$ HTTP_ORIGIN' ALWAYS;
        add_header 'Access-Control-Allow-Credentials' 'True' ALWAYS;
        add_header 'Access-Control-Allow-Methods' get, Post, Put, Patch, Delete, Options' Always;
        add_header 'Access-Control-Allow-Headers' 'ACCEPT, AUTHORIZATION, CACHE-CONTROL, CONTENT-TYPE, DNT, IF-MODIFIED-SINCE, KEEP-ALIVE, ORIGIN, USER-AGENT, X-Requested-with' Always;
    }
}

//Lumen
≪
? PHP
namespace app \ http \ middleware;
Use Closure;
Class CorsMiddleware
{
    /**
     * HANDLE AN INCOMING REQUEST.
     *
     * @Param \ Illuminate \ HTTP \ Request $ Request
     * @Param \ Closure $ NEXT
     * @return Mixed
     * /
    Public Function Handle ($ request, Closure $ NEXT)
    {
        //TODO: ACCESS-CONTROL-ALLOW-ORIGIN needs to be properly specified
        $ HEADERS= [
            'Access-Control-ALOW-ORIGIN'= >
 '*',
            'Access-Control-ALLOW-METHODS'= >
 'Post, GET, PUT, Delete, Options',
            'ACCESS-CONTROL-ALOW-CREDENTIALS'= >
 'True',
            'Access-CONTROL-MAX-AGE'= >
 '86400',
            'Access-Control-ALOW-HEADERS'= >'Content-Type, Authorization, X-Requested-with';
        //For PREFLIGHT request
        IF ($ request->
IsMethod ('options')) {
            Return Response ()->
JSON ('{"Method": "options"}', 200, $ headers);
        }
        $ RESPONSE= $ NEXT ($ REQUEST);
        Foreach ($ HEADERS AS $ KEY= >
 $ VALUE) {
            $ RESPONSE->
HEADER ($ KEY, $ VALUE);
        }
        RETURN $ RESPONSE;
    }
}

//WebPack.config.js
IMPORT PATH FROM 'PATH'
const src= path.resolve (__ DIRNAME, 'SRC')
const dist= path.resolve (__ DIRNAME, 'DIST')
module.exports= {
    MODE: "Development",
    Entry: ['@ babel /polyfill', src+ '/inDex.js'],
    OUTPUT: {
        Path: DIST,
        filename: "main.js"
    }
    Module: {
        Rules: [
            {
                //CSS
                Test: /\.css$ /
                EXCLUDE: {
                    include: /node_modules /
                    ///quill.js
                    EXCLUDE: /NODE_MODULES \ /REACT-QUILL \ //
                }
                USE: [
                    'Style-Loader',
                    {
                        Loader: 'CSS-Loader',
                        Options: {
                            URL: FALSE,
                        }
                    }
                ],
            }
            {
                ///JS
                Test: /\.js$/,
                EXCLUDE: /NODE_MODULES /
                USE: [
                    {
                        Loader: 'Babel-Loader',
                        Options: {
                            Presets: [['@ babel /Preset-env', {modulees: false}]]
                        }
                    }
                ]
            }
            {
                //TSX
                TEST: /\ .TSX ?$ /
                USE: "TS-Loader",
            }
            {
                //image
                TEST: /\. (JPG | JPG | JPEG | Png |PING | GIF |MP3 |SVG |TTF |WOFF2 | WOFF | EOT,
                USE: {
                    Loader: "File-Loader",
                    Options: {
                        name: "[name]. [EXT]",
                        OUTPUTPATH: "Assets /IMG",
                        PublicPath: PATH= >
 "/Assets /IMG /" + PATH
                    }
                }
            }
        ]
    }
    Resolve: {
        Extensions: [.ts "," .tsx "," .js "," .json "]
    }
    DevServer: {
        ContentBase: './dist',
        Host: '0.0.0.0',
        Port: 3000,
        inline: true,
        HistoryAPIfallback: True
    }
};

Version

LUMEN 6.3.3

To those who answered teraatail.com/questions/246761

htb2021-04-07 22:16:37

Nginx "add_header 'access-control-allow-origin: get, post, delete, put, patch, options');" In Access-Control-Allow-Methods?

yyz2021-04-07 22:16:37

Thank you for your reply! It was pointed out by Terateil, and I tried variously, but it was useless .... teraitail.com/questions/246761

khkhkh2021-04-07 22:16:37
  • Answer # 1

    Fixed PHP error, it worked properly! Thank you very much!
    As the cause, if an error occurs on the PHP side, the error message will be output before setting the CORS header, so the header is not output normally and it feels like it will be CORS error ...! CORS Error When the contents (error message) will be ignored.
    By the way, a class that does not exist as an error on the PHP side.

    Since it is a great deal of information (for the content of the question), I think it will be useful information for a third party if you write a little more than what to do.

    cubick♦2021-04-07 22:16:37