I am using Ajax to upload file to server. If I use it with the option withCredentials, the file is not uploaded to the server, although the post request itself is processed. If I post it without credentials, the file is uploaded to server. I need the option withCredentials set as true.
Form template:
<form class="upload" action="api_url" method="POST" enctype="multipart/form-data"><input type="file" name="file" id="file" /><br/></form>
Ajax submit:
jQuery( this ).ajaxSubmit({
data: data,
processData: false,
xhrFields: {
withCredentials: true
},
crossDomain: true,
error: function(xhr) {
console.log(xhr.status);
console.log(xhr.responseText);
},
success: function(response) {
}
});
Nodejs:
app.post( '/api/upload', cors(corsOptions), function( request, response ) {
var tmp_path = request.files.file.path;
var target_path = '/uploads/' + request.files.file.name;
fs.rename(tmp_path, target_path, function(err) {
if (err) {
console.log("rename error:");
console.log(err);
}
});
...
});
Result from the console:
rename error:
{ [Error: ENOENT, rename 'XXX']
errno: 34,
code: 'ENOENT',
path: 'XXX' }
If I check the upload location, the file has not been uploaded, although I can receive all the post data inside the server app.post method. I am using nodejs 'cors' module with the following options:
var whitelist = ['http://XXX'];
var corsOptions = {
origin: function(origin, callback){
var originIsWhitelisted = whitelist.indexOf(origin) !== -1;
callback(null, originIsWhitelisted);
},
credentials: true,
allowedHeaders: 'X-Requested-With, Access-Control-Allow-Origin, X-HTTP-Method-Override, Content-Type, Content-Range, Content-Disposition, Content-Description, Authorization, Accept'
};
All the other post methods are working with credentials, cross-browser. If I use ajaxSubmit with withCredentials set as false, the file is uploaded (no problems with file permissions).
What could be the problem? Any help is appreciated.
Thank you.