For cross-origin requests of WebUploader, webuploader cross-origin requests
Introduction: WebUploader is used to upload files in projects according to project requirements. When cross-origin is encountered, it is found that uploading is always failed. Many blogs are found online, and few of them are correct, what I explained was a little anxious for me. I finally solved the problem through sorting out and practice, and posted the solution to help other friends who encountered the problem.
1: When WebUploader is used, we will find that there are two requests when uploading, one is OPTIONS and the other is POST. This means that your api needs to be able to receive these two requests, for example:
$this->add("/index/save-file", array( 'controller' => "index", 'action' => "saveFile", ) )->via(["OPTIONS","POST"]);
Note: The above uses the phalcon route. Likewise, other frameworks are the same, such as any of laravel frameworks.
2: because it is a cross-origin upload, you must set the correct information and add the following at the beginning of your current method:
header('Access-Control-Allow-Origin: *');header('Access-Control-Allow-Methods: *');header('Access-Control-Max-Age: 1000');
Note: header ('access-Control-Allow-Origin: * ') This setting may cause security risks: You can, for example:
Header ("Access-Control-Allow-Origin: 'http: // localhost: 100'"); // 7779, the domain name address of your current api Project
3: because there are two requests, the first OPTIONS can "end it as soon as possible", such:
If ($ _ SERVER ['request _ method'] = 'options') {return $ this-> toSuccess (200, 'success ');}
4: After the above operations are OK, the operation should be smooth:
If ($ this-> request-> hasFiles () = false) {return $ this-> toError (500, "files not retrieved ");} $ Files = $ this-> request-> getUploadedFiles (); // get the file
... // Subsequent operations
5: if any error occurs, please correct it.