I am working on angular 4 app, In which, I have a requirement to upload a file on form submit, for this I am using ng2-file-upload plugin. But I faced a problem to upload file. I am creating a upload.php file completing uploading process. upload.php is as follow:
header("Access-Control-Allow-Origin: http://localhost:4200");
header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(array('status' => false));
exit;
}
$path = 'uploads/';
if (isset($_FILES['file'])) {
$originalName = $_FILES['file']['name'];
$ext = '.'.pathinfo($originalName, PATHINFO_EXTENSION);
$generatedName = md5($_FILES['file']['tmp_name']).$ext;
$filePath = $path.$generatedName;
if (!is_writable($path)) {
echo json_encode(array(
'status' => false,
'msg' => 'Destination directory not writable.'
));
exit;
}
if (move_uploaded_file($_FILES['file']['tmp_name'], $filePath)) {
echo json_encode(array(
'status' => true,
'originalName' => $originalName,
'generatedName' => $generatedName
));
}
}
else {
echo json_encode(
array('status' => false, 'msg' => 'No file uploaded.')
);
exit;
}
But I have got following error:
Failed to load http://localhost/uploads/uploads.php: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. Origin 'http://localhost:4200' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
If any help, please suggest me, thanks in advance!
This is a matter of browser secutiry, not Angular. When you make a crossdomain AJAX request, if you want to send cookies (basically, authorization information), browsers require that you specifiy an
Access-Control-Allow-Credentials
withtrue
, indicating that the external domain allows this. The reason for these two headers is because a site may allow AJAX requests from another domain, but maybe they don't want that domain to use any potential authorization cookies in the browser.As an example of what this risk entails, you could write an app to access Facebook' API via AJAX. But if Facebook allowed you to send cookies that may exist in the browser, you could make publications as if you were the authenticated user, which of course cannot be allowed. By preventing the sending of existent cookies, the user should have to give your app their facebook credentials to do something in their name.
As a complement to this check, sending cookies via XMLHttp also does not work if the
Access-Control-Allow-Origin
is set to '*'. Domains must be explicitly added, to ensure you don't give access to potentially dangerous sites.