How to close a request in nodejs? - node.js

What I have:
I'm using node.js with the express framework and I'm building a form where I can upload files, I'm using node-formidable for this.
What's the problem
My problem is that I can't close the request if I found an error with the uploaded files. I want to check file types, size etc.. So I can get the proper files uploaded, and the files are actually not uploaded so I don't waste time.
So the problem is that I can't stop the HTTP request.
What I have tried
Here is what I have tried so far:
request.connection.destroy();
response.end('something went wrong...');
I assume that the connection.destroy() aborts the request, and I know this because it fires the formidables form abort event (form.on('abort', function(){ ... })) But the file is still uploading, and the response doesn't arrives just after the file was uploaded.
So how should I close the HTTP Request, and send a message back to the client?
EDIT:
And something else, when I don't use response.end() then it works, except that the Client waits for the the answer, it's weird :\

The correct way for doing this is:
request.pause();
response.status = 400;
response.end('something went wrong...');
Source: https://groups.google.com/forum/?fromgroups=#!topic/nodejs/2gIsWPj43lI

Try with following code:
When your server side validation fails, give a response like:
res.json({'IsFileUploaded':'false', 'requiredFileSize': '1000bytes', 'actualFileSize': '800bytes', 'AlertMsg':'File size should be at least 1000 bytes....'})
It closes connection as well as you can pass your data in JSON format

Related

Nestjs multer upload file after some codes

I am developing an api based on nestjs. I used multer package to upload file. The code sample on nestjs documentation is at the following:
#Post('upload')
#UseInterceptors(FilesInterceptor('files'))
uploadFile(#UploadedFiles() files: Array<Express.Multer.File>) {
console.log(files);
}
But I want to save uploaded file after send mail. If the mail sends successfully then I will save the file. If sending mail process is fail, I ignore the file uploding.
How can I figure out?
You could do this in two ways, One is to create another route like#Post('mail') then depending on the response you receive in your client, let's say it returns an OK you can send another request to upload the files, or you can send both the requests to your API at the same time then cancel uploading the files (supposing this request takes longer to complete) if sending the mail was not successful (for this you need to handle errors that might result in incomplete files in your API, basically your API should know the full size of the files to expect so that you can compare if there was no cancellation).
The other way is using one route to do both of the tasks, in your example add the code for handling sending the mail and based on the condition that it went successfully do or don't proceed with uploading the files.

why is my data undefined when i make an http request?

I have a problem with my backend when I send my data to the API req.body sends me null {}
suddenly I don't understand why I can't recover my data, however on the front side I send the data well ?
if you're using form data then include url encoded parser like this::
app.use(express.urlencoded({extended : true}));
app.use(express.json());
add this in your main server file where you create your server
It may be the order of variables, haven't tried, but that is the only thing that sticks out. When you are sending its {email,name,password2,password} but when you are receiving it its {name,email,password,password2}
Edit: messed up variable orders when replying ironically

Unable to get redirect response from Node server using res.writeHead() and .end()

I'm writing a server in Node.js. I've been using the send-data/json package to send responses, with much success. For example, at the end of my API call I use this code:
sendJson(res, res, {some: content})
This works great. However, I have a need to implement a URL redirect in one of my API endpoints. The code I am seeing everywhere to do this looks like this:
res.writeHead(302, {Location: 'http://myUrl.com'})
res.end()
However, this change causes my server to stop sending responses on this endpoint.
What am I missing?
Note: this is vanilla Node without Express.
Update: to clarify, based on contributions in the comments, this is the result of a GET request, so I expect that redirects should be enabled by default. I am still curious why no response is coming back from the server at all, regardless of whether it is an erroneous redirect attempt or a successful one.

how to send just a 200 response in express.js

I have node.js 5.2.0, express 4.2.0 and formidable 1.0.17.
I created a simple form to save a textfield and a photo. It works fine, but the problem is, after the data are uploaded, I can see in the console that the POST is not finished, its still Pending.
In order to finish it I added this to my code
form.on('end', function() {
res.writeHead(200, {'Content-Type': 'text/plain'});
});
I just want to send the headers and nothing on the page. I want the system to get a 200 ok response without having to print anything on the page. But the POST is still pending.
How do I fix this, without having to print anything? What kind of headers I have to send?
Thanks
UPDATE
If I do
form.on('end', function() {
res.end();
});
The POST finishes normally, but I get a blank page. Why is that? I just want to upload some stuff, not print anything on the page, not redirect, stay in the same page.
Thanks again
Try this instead:
res.sendStatus(200);
Or if you want to continue using explicitly defined headers, I believe res.end() needs to be called at some point. You can see how res.end() is utilized in the Formidable example.
The blank page is most likely the result of your client-side form handling. You may want to override the form's submit method and manually post to your express service to prevent the automated redirection you are seeing. Here are some other stackoverflow responses to a question involving form redirection. The answers are jQuery specific, but the basic idea will remain the same.

Express (node.js) seems to be replacing my content-type with application/json

I've written an express web app route that is essentially a proxy - it pipes the contents of an input stream (a zip file) into the server response's output stream.
I'd like the browser to prompt the user for download or whatever is most appropriate for a zip file. However, when I load this route in a browser, the contents of the input stream (the zip file's contents) show up in the browser window as text, rather than prompting a download. l
This is the code sending the response:
res.statusCode = 200;
res.setHeader ('Content-Length', size);
res.setHeader ('Content-Type', 'application/zip');
console.log ("content-type is " + res.header('Content-Type'));
inputStream.pipe (res);
The console.log statement above outputs "content-type is application/zip".
However, when I examine the request in Chrome's network tab, I see that the response's content-type is "application/json". This implies that express, or something else, is overriding my content-type header, or perhaps has already sent it.
Does anyone know what is changing the content-type on me, and how I could make sure the content-type is the one I set?
Thanks for any help.
You should check the order of the middleware, it's really tricky and can mess things up if they are in the correct order.
You can check the correct order here in the Connect webpage

Resources