Uploading files using node.js with the help of express, multer, fast-csv

Currently, I am attempting to implement a file upload functionality using pug, multer, and express.

The structure of the pug form used for uploading a file is as follows:

form(method='POST' enctype="multipart/form-data")
    div.form-group
    input#uploaddata.form-control(type='file', name='uploaddata' )
    br
    button.btn.btn-primary(type='submit' name='uploaddata') Upload

Here is a snippet of the server code (provided out of context):

.post('/uploaddata', function(req, res, next) {
    upload.single('uploaddata',function(err) {
    if(err){
      throw err;
      } else {
    res.json({success : "File upload sucessfully.", status : 200});
    }
  });
})

My main issue currently is that although the file uploads successfully, the success message does not display on the same page; instead, a new page loads showing:

{success : "File upload sucessfully.", status : 200}

For other elements such as link clicks, a javascript function is used to display messages, like this example:

$("#importdata").on('click', function(){
        $.get( "/import", function( data ) {
            $("#message").show().html(data['success']);
        });
    });

I have tried pure JavaScript solutions to bypass the default form behavior, but so far, no luck has been achieved.

Answer №1

The issue you are facing is related to the combination of form submissions and AJAX concepts. Specifically, your current approach involves submitting a form while expecting a response suitable for an AJAX API. To resolve this problem effectively, you must decide whether to stick with traditional form submission or fully embrace AJAX methods.

If you opt to continue using form submission, it's essential to note that you cannot utilize res.json. Instead, consider using res.render or res.redirect to refresh the page appropriately. The outcome you are observing—JSON output—is directly tied to the instruction given to node/express through res.json. Implementing rendering or redirection functions is crucial in this scenario.

You may refer to the MDN guide on forms as well as a tutorial specific to express.js for further assistance.

On the other hand, if you decide to handle the process through an AJAX API, employing tools like jquery, fetch, axios, or similar technologies in the browser is necessary to send requests and manage responses effectively. While this approach avoids page reloading, it requires careful handling of responses to update the page content promptly for a seamless user experience.

For those exploring AJAX implementation, delving into resources such as the MDN AJAX primer and insights on restful API design can provide valuable guidance.

Both strategies have their merits and are commonly utilized in large-scale applications. However, it is imperative to make a clear choice between the two approaches without mixing them, as demonstrated in the context above.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Auto-refresh the page upon any updates made to the MongoDB collection

I'm currently working on a Node.Js project that involves MongoDB integration. I'm looking for a way to automatically refresh one of my HBS pages whenever there is a change in my MongoDB collection. I could use some guidance on the best approach ...

Verify the user's activity status in the MySQL database using Node.js by checking the timestamp of their last login

I have a query regarding user activity and deletion from the database. I need to determine when a user last logged in to see if their account is inactive. Unfortunately, I am unsure of how to tackle this task or check for the last login time. If anyone c ...

Exploring multipart uploads in Express JS 4: Leveraging body parser and dicer for efficient file handling

Currently, with express 4 and body-parser set up as shown below: var bodyParser = require('body-parser'); ... app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); After integrating dicer, it seems like body parser ...

Is there a way to retrieve a session variable within an EJS view template?

After a user logs in, I would like to store their details in the session and be able to access them in ejs templates. How can this be accomplished? app.post('/registration', function(req, res) { var name = req.session.user_name = req.body.us ...

Issue with Mongoose: Subdocument fails to update when parent document is updated

Struggling with this issue for some time now, I have 2 schemas: **User Schema** const mongoose = require('mongoose'); const PaymentSchema = require('../models/payments').schema; const UserSchema = new mongoose.Schema({ firstname :{ ...

Encountered an issue locating the view within the directory while using Express Handlebars

I've been working with the basic app layout generated by Express Generator and I'm trying to customize it for Handlebars. Snippet: var exphbs = require('express-handlebars'); var app = express(); // view engine setup app.set('v ...

Socket.io encounters emitting issue within express app.post function

I am working on integrating an express application with a frontend React application using socket connections. My goal is to trigger an event on the connected socket whenever a post request containing JSON data is sent to my server. However, I am facing a ...

(updated solution) The Express web app service is encountering an error message stating "SyntaxError: Unexpected token >"

I recently deployed my web app to two Azure app services and encountered different results - one is working fine, while the other is throwing an error. My web app is built on Express and I am unsure how to resolve this issue as the error does not seem to ...

Guide on Utilizing Forever Alongside Express for Continuous Operation of a NodeJS Server

Currently, I have an Express NodeJS server that I personally initiate via the terminal with npm start in the root directory of my project. To ensure consistent uptime, I opted to install the Forever package globally. However, when I try to run Forever on m ...

Is it possible to integrate the Firestore npm library into my Express application?

Recently, I created my own library to act as a nosql database on my node.js web server in place of mongodb. I came across this interesting quote: Applications that use Google's Server SDKs should not be used in end-user environments, such as on pho ...

Tips for uploading a file and submitting form data with Angular2, using [(ngModel)], and then storing the reference in MongoDB

Currently, I am working on a task page and I need to implement the functionality to upload a file along with the form submission to the NodeJs express server. @Component({ selector: 'tasks', template: `<div mdl class="mdl-grid demo-c ...

Integrating individual front end JavaScript files into an Express.js application

I've been working on a JavaScript file that contains over 200 lines of code for the front end logic of my project. It handles interactions like button clicks, image displays, and more, similar to a game. However, I'm struggling to figure out how ...

The jade code is causing an error to be displayed

The following Jade code seems to be malfunctioning. head script(src='http://d3js.org/d3.v3.min.js') script(src='http://dimplejs.org/dist/dimple.v2.1.0.min.js') body script(type='text/javascript') var svg ...

Unforeseen Problem: Mocha ES6 Node App Glitch

Encountering an ES6 import issue in Mocha test cases currently. Even after attempting to add the latest Babel and presets, the issue remains unresolved. Various solutions have been tested but none seem to fix the problem. This snippet shows my package.jso ...

Save the socket.id from Socket IO into the Express session

Currently, I am working on a web application that utilizes Angular and Express. To handle database updates, I have implemented a REST API and incorporated SocketIO for real-time client updates. I have managed to track a list of active socket IDs for each ...

Exploring the MEVN Stack's Integration with Image Uploading

After successfully implementing an image upload system on my website, I encountered difficulty in linking to the uploaded images. The root directory of my project includes a client folder for vuejs app and a server folder for backend logic. When users upl ...

Is there a way to pass a hyperlink as a parameter in Express?

I am attempting to pass a hyperlink (like: "") as a parameter to my Express server script. The current setup of my script is as follows: var app = require("express")(); app.get("/new/:link(*)", function(req, res){ var link = req.params.link; res. ...

What could be the reason for my button not updating its text using a method?

I attempted to change the inner text of the Edit button to Save after it's clicked using a method, but it doesn't seem to be working. I could really use some help with this. b-button.editbtn.d-flex.flex-row.mb-3(@click="editBlood") ...

What is the best way to access details about a logged-in user in Node.js?

Is there a way to retrieve information about the currently authenticated user in Node.js (specifically Express.js), similar to using Auth::user() in Laravel framework? Appreciate any guidance on this. Thank you. ...

Does TypeGraphQl have the capability to automatically format SQL queries?

I am utilizing TypeORM in conjunction with TypeGraphQL. I am curious about the SQL query result that TypeGraphQL provides. For instance, if I have a User Table with numerous columns and a simple resolver like this: @Resolver() class UserResolver { @Q ...