How to easily transfer a JSON file to a server using Vue and Node.js

As a newcomer to the world of Node.js and Vue development, my goal is to establish a seamless process for users to create and upload a JSON file to the server when they save data in a form. This process should occur effortlessly in the background, allowing for smooth operation. Additionally, I aim to enable users to read and update this file on the server whenever changes are made.

In my initial attempt, I considered using fs.writeFile(). However, it appears that this method may not be suitable for handling remote tasks. Is my assumption correct?

var fs = require('fs')

export default {
  methods:{
    send(){
      fs.writeFile("/test.json","Hello World!",function(err){
        if(err){
          throw err;
          } 
      });
    }
  }
}

Furthermore, it seems that using fs.writeFile with Vue results in an error:

TypeError: fs.writeFile is not a function at VueComponent

Consequently, my alternate approach involves looking into Express.js and utilizing the app.post('/api/apps',...) and app.get() methods. However, integrating this with the Vue framework presents some challenges as accessing the API via 'mydomain.com/api/apps' does not yield the desired outcome.

What would be the optimal way to handle file creation, reading, uploading, and deleting within a specific directory on the server? How can this be achieved seamlessly with Vue? My inclination leans towards using Express.js.

I'm currently working with Vue CLI :)

Thanks in advance :)

EDIT

My current approach involves:

I have set up a new folder named "backend" within my Vue project root directory. Inside this folder, I created a file named index.js containing the following code:

    app.post('/appjson',(req,res) => {
        fs.writeFile("/appjson/myJson.json",req.body,function(err){
           //handle error
        });
    }); 

On the client-side, I implemented the following code:

axios.post('myDomain.com/appjson', {
  JSONdata: myJSONdata,
})

This strategy allows me to successfully deploy the dist folder on my server, facilitating smooth operation. However, I encounter difficulties in calling the backend. Am I using the incorrect link? How can I access my backend effectively? Is there any need for adjusting the project structure or relocating the backend to a different folder?

Answer №1

Vue operates on the client side, so attempting to write directly to a user's filesystem from your website is not possible. Instead, you should send the data to your NodeJS server using a tool like Axios to facilitate communication without refreshing the page. The process of utilizing Axios is fairly simple and can be implemented as shown in the example function below.

  saveJSON (myJSONData) {
const url = myNodeJSURL/savescene
return axios.post(url, {
  JSONdata: myJSONdata,
})

Consider studying some tutorials on ExpressJS, which is an intuitive framework for handling this scenario. By extracting the data from the body of the HTTP request, you can utilize fs.writeFile to store information on the local filesystem of your server. Reach out if you need further assistance.

EDIT: To establish communication between the front end and back end, your front end must have access to the domain or IP address associated with your backend system. Integrate the code snippet provided into your ExpressJS application, allowing any requests to localhost:3000 to be managed by your app once it is launched. Don't forget to update the URL specified in your Axios call accordingly.

app.listen(3000, function () {
  console.log('my server is listening on port 3000!')  
})

Note that this setup is primarily designed for testing purposes due to the necessity of both client and server being situated on the same device for localhost references to align properly. If you intend for your project to be accessible to the public, consider obtaining your own domain name for hosting the ExpressJS application. Google Compute provides convenient solutions for this aspect, so it may be worth exploring their services for your project's deployment.

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

The specified <model> has not been declared

Within my codebase, I have defined multiple schemas. One of them is functioning perfectly: var mongoose = require('mongoose'), Schema = mongoose.Schema; var NewsSchema = new Schema({ name: String, route: String, remoteU ...

Guidelines for deploying a node.js REST API application successfully in a production environment

As I venture into the world of node.js apps, I find myself faced with a dilemma. I've created a REST API using node.js that functions perfectly on my local machine. However, when I attempt to build it using webpack, I'm uncertain about how to run ...

Unspecified property in Vue.JS data object

Whenever I try to display my modal, an error pops up indicating that the property is not defined, even though I have clearly declared it in the Data(). It seems like there is a crucial aspect missing from my understanding of how everything functions... T ...

Using ES6 Babel with multiple package.json files

For a large project, I am looking to break it down into multiple package.json files. This way, the dependencies for each part can be clearly defined and exported as separate entities. However, my goal is to compile all of these packages using webpack and ...

Use the npm command key to globally install a package

My attempt to globally install gulp on OS X has led to a perplexing discovery. Initially, I used the command: npm install -g glup This resulted in an error message: npm ERR! Darwin 14.4.0 npm ERR! argv "node" "/usr/local/bin/npm" "install" "-g" "glup" n ...

Save the content of a string object into an array

I am currently implementing an array sorting functionality using the MVC approach. The array called "array" is used to store values provided at runtime. Within the view, there is a textbox and a button for user input of integer values. Upon clicking the bu ...

Transform an HTML table string into JSON format

I discovered a useful library called table to JSON that allows me to convert an HTML Table to JSON using its ID (#testtable in the example below): var table = $('#testtable').tableToJSON(); alert(JSON.stringify(table)); However, I am interested ...

Node.js uses Firebase Admin to send notifications to a different service account

Exploring two different routes in nodejs. Let's start with one.js var admin = require("firebase-admin"); var topic = "/topics/news"; var serviceAccount = require("/path/serice-1-firebase-adminsdk.json"); var firebase = admin.initializeApp({ cred ...

Combining two authentication tokens in a single endpoint

I'm facing a challenge where I need to combine 2 authentication tokens in one endpoint - the user and admin tokens - to access all merchants. Despite trying various solutions suggested on stackoverflow, none seem to work for me. Below are my code sni ...

Only include unique objects in the array based on a common property

I am currently working with the following array: [ {name: "Mike", code: "ABC123"}, {name: "Sarah", code: "DEF456"}, {name: "John", code: "GHI789"}, {name: "Jane", code: "JKL01 ...

Combining Extjs combo with autocomplete functionality for a search box, enhancing synchronization capabilities

When using autocomplete search, I've encountered an issue. If I type something and then make a mistake by deleting the last character, two requests are sent out. Sometimes, the results of the second request come back first, populating the store with t ...

How can we implement a select-all and deselect-all feature in Vue Element UI for a multi-select with filtering capability?

As a newcomer to VueJs, I am exploring how to create a component that enables multiple selection with a search option and the ability to select all or deselect all options. To achieve this functionality, I am utilizing the vue-element-ui library. You can ...

Is it possible to view the object sent from AJAX to PHP in PHP using a debugger?

I'm facing an issue where I am making an AJAX call to a PHP file, sending a JSON object as a parameter from JavaScript. The PHP file is supposed to perform some logic with the object and return it using json_encode('whatever');. However, the ...

Using a HTML tag within vue js

Is it possible to dynamically change a <p> tag inside my component to be an <h1> tag based on a prop? If so, how can this be achieved? <template> <p>Hello world</p> </template> ...

Having trouble displaying HTML UL content conditionally in Reactjs?

My goal is to display a list of items, limited to a maximum of 5 items, with a "more" button that appears conditionally based on the number of items in the list. However, I am encountering an issue where passing in 5 li items causes them to be rendered as ...

Difficulty encountered while executing Protractor tests with Selenium Server

Attempting to Execute Protractor/Jasmine/Selenium End-to-End Tests Currently in the process of running end-to-end tests using Protractor with the standalone Selenium server and the chrome driver. Encountering a Selenium server error when attempting to ru ...

Having trouble with my Express app due to errors popping up because of the order of my routes

app.get('/campgrounds/:id/edit', async (req,res) =>{ const campground = await Campground.findById(req.params.id) res.render('campgrounds/edit', { campground }); }) app.get('/campgrounds/:id', async (req,res) =>{ ...

Modifying .vue files within Laravel seems to unexpectedly impact unrelated CSS styles

I've been working on a Laravel project that involves building Vue components. Strangely, every time I update a .vue file and add it for a commit, modifications are also made to the app.css and app.js files. These changes seem to be undoing a particula ...

I am using node.js with an express server, and I want to display any errors that I see in the console on my webpage as well

I have set up a Node.js Express server on Glitch website like this: const express = require("express"); const app = express(); const port = 3000; const server = app.listen(port, () => console.log(`App listening on port ${port}!`) ); Additionally, ...

Continuous scroll notification within the fixed menu until reaching the bottom

I'm looking to achieve a scrolling notification message that stays fixed at the bottom of a top-fixed menu while the body content continues to scroll normally. Here's an example in this fiddle: HTML: <div class="menu-fixed">I am a fixed me ...