Where get response ngx-uploader? - ngx-uploader

I have a JSON response back from my url for my uploads but in code I can't get it, can you suggest where and how I can get it?
onUploadOutput(output: UploadOutput): void {
if (output.type === 'allAddedToQueue') {
const event: UploadInput = {
type: 'uploadAll',
url: this.url,
method: 'POST',
data: {foo: 'bar'}
};
this.uploadInput.emit(event);
........
} else if (output.type === 'done') {
this.files.forEach(file => {
console.log('ciao'); //DIDN'T WORK
console.log(file.response); //DIDN'T WORK
this.uploadInput.emit(file.response);
});
}
this.files = this.files.filter(file => file.progress.status !== UploadStatus.Done);
}
}

Found a solution, edit ngx-uploader module and change this code about line 236 in ngx-uploader.js:
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
/** #type {?} */

Related

Stop node mailer scheduler after 3 days of subscribing to newsletter

I have a node.js application and I am using node mailer. When user subscribes to newsletter I send him newsletter every day at specific hour. How can I achieve that it will stop sending to that specific user after 3 days.
Code in MailServiceCron.ts:
export const CRON = () => {
scheduleJob("0 5 * * *", async () => {
try {
let UserList = await User.getUsersByDate();
UserList.forEach(async (user: IUserGet) => {
var content = fs.readFileSync("src/data/email.html");
var htmlbody = content.toString();
await fetch(
"api_url" +
process.env.USER_KEY,
{
method: "POST",
headers: { "Content-Type": "application/json" },
}
)
.then(async (res) => {
return [await res.json(), res.status];
})
.then(([data, status]) => {
console.log(data);
if (data.steviloDelovnihMest > 0) {
let transporter = nodemailer.createTransport({
host: "host",
port: 25,
secure: false, // true for 465, false for other ports
});
let info = transporter.sendMail({
from: "<no-reply#text.com>", // sender address
to: user.email, // list of receivers
subject: `test`, // Subject line// plain text body
html: htmlbody, // html body
});
}
})
.catch((error) => {
return console.log(error);
});
});
console.log("Sending mails");
} catch (e) {
console.log(e);
}
});
};
function deleteEmptyProps(obj: any): any {
Object.keys(obj).forEach((k) => {
if (
!obj[k] ||
obj[k] === undefined ||
(Array.isArray(obj[k]) && obj[k].length === 0)
) {
delete obj[k];
}
});
return obj;
}
export const deletingNonActiveCRON = () => {
scheduleJob("0 * * * *", async () => {
try {
let response = await User.deleteNonActive();
console.log(response);
} catch (e) {
console.log(e);
}
});
};
And in my separate file mail.ts i have this:
module.exports.deleteNonActive = async function () {
let date = new Date();
return await User.deleteMany({
$and: [
{ dateStart: { $lt: new Date(date.setHours(date.getHours() - 48)) } },
{ aktivnost: { $eq: false } },
],
});
};
My idea is that I need also some deleteExpired function, something like that?
module.exports.deleteExpired = async function () {
await User.updateMany(
{
$and: [
{ dateEnd: { $lt: new Date() } },
{ aktivnost: { $eq: true } },
],
},
{ $set: { aktivnost: false } }
);
};
Which I also call in MailServiceCron.ts file like deleteNonActive function?

Axios Keeps setting my content type as multipart/form-data; boundary=----WebKitFormBoundary When I have JSON data

I have tried many things including adding the headers to the request. Still does not work. I have looked everywhere and came here as a last resort.
My main.js (routes)
app.post("/timeclock/punchout", async (req, res) => {
let time = moment().unix();
let employeeid = req.body.empid2;
let date = moment().format();
let comments = req.body.comments;
return res.send({ error: false, message: "complete punch" });
});
my liquid file using jQuery and axios
<script>
toast = siiimpleToast.setOptions({
container: 'body',
class: 'siiimpleToast',
position: 'top|right',
margin: 15,
delay: 2,
duration: 3000,
style: {},
})
$("#form").submit(function(event) {
event.preventDefault()
let empid1 = $("#empid").val()
let comments1 = $("#comments").val()
axios.post('/timeclock/punchin', {comments: comments1, empid: empid1}).then(response => {
if(response.data.error == false) {
$("#form").trigger('reset')
toast.success('Punch Successful!')
} else if(response.data.error == true) {
toast.alert(response.data.message)
$("#form").trigger('reset')
}
}, (error) => {
console.log(error)
})
})
$("#form").submit(function(event) {
event.preventDefault()
let empid1 = $("#empid").val()
let commentsout1 = $("#commentsout").val()
axios.post('/timeclock/punchout', {commentsout: commentsout1, empid: empid1}).then(response => {
if(response.data.error == false) {
$("#form").trigger('reset')
toast.success('Punch Successful!')
} else if(response.data.error == true) {
toast.alert(response.data.message)
$("#form").trigger('reset')
}
}, (error) => {
console.log(error)
})
})
any ideas? I read that it automatically detects the content type. But I cant seem to override it.

Send multiple files from express server to rest api

I am trying to send multiple files from react to express server and then to microservice. The problem is that my express server is getting crashed whenever I try to upload multiple files.
Here is my express.js side code:
router.post("/upload-files", upload.array("file[]"), async function (req, res) {
let check = new FormData();
// check = req.files;
const file = req.files;
// console.log("DATA------------------------>", file);
// check.append("file", file.buffer, file.originalname);
await axios.post(
constants.URL2 +":9095/upload-files", check,
{
headers: {
...check.getHeaders(),
},
})
.then((res) => {
return res;
})
.then((result) => {
res.send(result.data);
});
});
Here is my React.js side code:
update = () => {
if (this.isValidForm()) {
$(".loader").css({ display: "block" });
$(".overlay").css({ display: "block" });
// const obj = {
// fullName: this.state.fullName,
// };
var formData = new FormData();
const size = this.state.fileData;
for (let i = 0; i < size.length; i++) {
console.log(this.state.fileData[i]);
formData.append("file[]", this.state.fileData[i]);
}
// formData.append("files", this.state.fileData);
const updateRequest = {
method: "POST",
headers: {
// "Content-Type": "application/json",
Authorization:
},
// body: JSON.stringify(obj),
body: formData
};
fetch(URL.BASE_URL + "upload-file", updateRequest)
.then((res) => {
if (res.status == 401) {
this.props.GETLOGGEDINUSER(null);
this.props.history.push("/");
} else {
return res.json();
}
})
.then((res) => {
if (res.statusCode == 0) {
this.props.history.push({
pathname: "/newScreen",
state: { notification: "File uploaded Successfully" },
});
toast.success("File uploaded Successfully");
$(".loader").css({ display: "none" });
$(".overlay").css({ display: "none" });
} else {
toast.error(res.message);
$(".loader").css({ display: "none" });
$(".overlay").css({ display: "none" });
}
});
} else {
}
};
I tried many ways to solve this but none of them works.

Pass Object to Node JS GET request

I am trying to pass an object to my NodeJS server from my angular application. I can read the object perfectly fine on the client-side, but not serverside.
Here is my client-side:
var query = {
date: '9-2-2019',
size: 4
}
this.http.get<any>(url, {params: {query: query} }).toPromise();
Why can I not pass this to my Node JS server?
No overload matches this call.
Is my error.
Please change { params: {query: query}} to be {params: query} and also change query.size to be string instead of number
var query = {
date: '9-2-2019',
size: '4'
}
this.http.get<any>(url, {params: query}).toPromise().then(response => {
console.log(response);
})
.catch(console.log);
Alternative
Create // utils.service.ts
import { HttpParams } from '#angular/common/http';
// ...
export class UtilsService {
static buildQueryParams(source: Object): HttpParams {
let target: HttpParams = new HttpParams();
Object.keys(source).forEach((key: string) => {
const value: string | number | boolean | Date = source[key];
if ((typeof value !== 'undefined') && (value !== null)) {
target = target.append(key, value.toString());
}
});
return target;
}
}
then use it in your service
import { UtilsService } from '/path/to/utils.service';
var query = {
date: '9-2-2019',
size: 4
}
const queryParams: HttpParams = UtilsService.buildQueryParams(query);
this.http.get<any>(url, {params: queryParams }).toPromise().then(response => {
console.log(response);
})
.catch(console.log);

Upload File Using NPM Request from new Formdata()

i'am develop backend using node-js and https://www.npmjs.com/package/request to handdle request to main api.
has successfully to send data in the form of string or a number. but I have a problem to send the file. before getting to the request module, i have convert all request from client using
new formdata()
end this is what i code using NPM request
export function requestAPI(method='GET', endpoint='', params={}, callback)
{
let token = ''
if(params.token)
{
token = params.token;
delete params.token;
}
//set query
if(params.query)
{
endpoint = `${endpoint}?${Url.serialize(params.query)}`
delete params.query
}
//set options
let options = {
method: method,
uri: `${process.env.API_HOST}${endpoint}`,
timeout: 6000,
headers: {
'auth' : token
},
};
// upload files
// ???
// using POST method
if(method === 'POST') {
options['form'] = params;
}
// is upload a file - request via multipart/form-data
//start request
try {
request( options , function(error, response, body){
if(error)
{
console.log(error)
return callback(httpException(500));
} else //success
{
return callback(JSON.parse(body));
}
})
} catch(err) {
return callback(httpException(500, err.message+', '+err.stack));
}
}
For sending files you will need to use something like multipart/form-data instead of application/json. In addition, you will need to use the formData option instead of form. For example:
var options = {
method: method,
uri: `${process.env.API_HOST}${endpoint}`,
timeout: 6000,
headers: {
'auth' : token,
},
};
// using POST method
if (method === 'POST') {
options.formData = params;
}
Then inside params you can use any values as outlined in the request and/or form-data modules' documentation. So for local files, you can just use a readable stream:
var fs = require('fs');
// ...
params.avatar = fs.createReadStream('avatar.jpg');
For files you can explicitly set a different filename and/or mime type as shown in the relevant request multipart/form-data example.
thanks for help guys, finaly i found the answer to solved it.
the problem on this line
if(method === 'POST') {
options['form'] = params;
}
i just change to this, to make it works
if(method === 'POST') {
options['formData'] = params;
}
and this is the complete of codes
export function requestAPI(method='GET', endpoint='', params={}, callback)
{
let token = ''
if(params.token)
{
token = params.token;
delete params.token;
}
//set query
if(params.query)
{
endpoint = `${endpoint}?${Url.serialize(params.query)}`
delete params.query
}
//set options
var options = {
method: method,
uri: `${process.env.API_HOST}${endpoint}`,
timeout: 30000,
headers: {
'auth' : token
},
};
// using POST method
if(method.toLowerCase() === 'post') {
options.formData = params;
// upload files
if(options.formData.files)
{
const files = options.formData.files
delete options.formData['files']
Object.keys(files).map(n => {
options.formData[n] = {
value: fs.createReadStream(files[n]._writeStream.path),
options: {
filename: files[n].name,
type: files[n].type
}
}
})
}
}
//start request
try {
request( options , function(error, response, body){
if(error)
{
return callback(httpException(500));
} else //success
{
return callback(JSON.parse(body));
}
})
} catch(err) {
return callback(httpException(500, err.message+', '+err.stack));
}
}

Resources