Node application sends requests successfully, whereas in JS (Vue), the request is not functioning properly

Greetings! I have a backend that receives a request with an image for storage. When testing it with Postman and the code snippet below, everything works perfectly:

var axios = require('axios')
var FormData = require('form-data')
var fs = require('fs')
var data = new FormData()
data.append('file', fs.createReadStream('index.png'))
console.log('HEADERS')
console.log(data.getHeaders())
let config = {
  method: 'post',
  url: 'http://localhost:5013/v1/business/honda/widget/test/',
  headers: {
    ...data.getHeaders(),
  },
  data: data,
}

However, the issue arises in my Vue app when attempting to replicate the process with the following code. I have two buttons - one to load the image and the other to send it. Upon sending the image to the backend, I encounter the error message 'http: no such file'.

To rectify this issue, refer to the modified code snippet below:

 let imageData
// Function to send the image to the backend
function funtest() {
  console.log('image')

  const formData = new FormData()
  const url = 'http://localhost:5013/v1/business/honda/widget/test/'

  formData.append('file', imageData)
  let config = {
    method: 'post',
    url: url,
    headers: {
      'Content-type': 'multipart/form-data',
    },
    data: formData,
  }
  axios(config)
    .then((response) => {
      console.log('RESPONSE')
      console.log(response)
    })
    .catch((error) => {
      console.log('ERROR')
      console.log(error)
    })
}

// Function to read the image 
function onImage(data) {
  const reader = new FileReader()
  reader.onload = (e) => {
    imageData = e.target.result
    console.log('image')
  }
  reader.readAsDataURL(data.target.files[0])
}

Answer №1

It seems like there might be an issue with reading the path to the index.png file correctly in this scenario, specifically with fs.createReadStream('index.png')

You could try utilizing the path module in the following manner

const path = require('path');

const filePath = path.join(__dirname, 'index.png');

data.append('file', fs.createReadStream(filePath))

Note: This is just a rough suggestion and may not work flawlessly, but it's definitely worth trying out

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

Maintain the username data after refreshing the page in React by utilizing local storage

I'm attempting to manage the value of username using local storage. Upon page load, the user should be greeted with a heading that says welcome John. Additionally, I want this value to persist when the page is reloaded. However, upon loading the page ...

Executing a Python function using JavaScript: Step-by-step guide

I am facing an issue with invoking my python function from my javascript file. Running a simple server with python3 -m http.server, I have no backend and all my javascripts are on the front end. In a python file named write.py, there is a function that I ...

Designing access to data in JavaScript

As I work on developing my single page app, I find myself diving into the data access layer for the client-side. In this process, a question arises regarding the optimal design approach. While I am aware that JavaScript is callback-centric, I can't he ...

Discover the position of a dynamic accordion using jQuery

After making an AJAX call, I am able to generate a list of accordions like this: data.items.forEach(function(item,index) { if(item.desciption != "") { $('#accordionList').append( create ...

Tips for properly removing Bootstrap 4 tooltips when deleting their corresponding DOM element using html()

In my Bootstrap 4 project, I've implemented a live search box that displays results with tooltips for longer descriptions. I've written jQuery scripts to hide the search results and their parent div when certain events occur, like clearing the se ...

Locate a specific cell within a PrimeFaces datatable using JQuery

I am relatively new to Primeface and JQuery. I have a datatable that I need to access a specific cell in using jQuery. Here is what I am attempting to achieve: Here is the code for my Datatable: <p:dataTable id="employeeDataTable" var="employee" value ...

Obtaining the date for the previous month using JavaScript or jQuery

I need to retrieve a specific date in JavaScript. My goal is to obtain the current date based on a variable named frequency, which can have values of Daily, Weekly, or Monthly. if(frequency=="daily") { date='current_date -2 days'; } e ...

Using parameters in Vue router

Having some trouble here. Can't seem to make it work. I've got this component called Project. Inside, there's this block of code: When I click on project, I want it to navigate to another detail page but nothing happens: {path: '/det ...

A single channel for handling numerous paths in Angular 2

I am currently working on configuring AngularJS 2 routes. Within my project, I have designed a layout that consists of a fixed header, dynamic sidebar, and dynamic content. In order to navigate through the application smoothly, I have set up the following ...

Executing Child Validators when moving to the next step in an Angular MatStepper from the Parent Component

I am looking to implement validation for my Mat-Stepper-Next function in the App Component using child component validators. I have 3 different form components, each with its own form group, validations, and next button within the component. I am includi ...

Combining multiple API GET requests into a single list to generate a consolidated Dataframe

Struggling to convert a list of 16 API GET results into a dataframe. The raw data is in the format: ['{"total":17,"result":[{"categories":[],"created_at":"2020-01-05 13:42:19.576875","icon_url&qu ...

How can I send parameters to an HTML file using Node.js?

In my current code res.sendfile('./home.html',{user:req.user}), I need to figure out a way to access the user parameter directly in the HTML file without relying on a template engine. Can anyone suggest how this can be achieved? ...

The database does not get updated by an Ajax request without a page refresh

I'm currently in the process of developing a dashboard system and I've created a ToDo list for it. The main functionality of the system is to allow users to add, delete, and mark tasks as finished or unfinished. I am using codeIgniter for this p ...

Read and manipulate website content using PHP

I recently encountered a challenging situation as a newcomer. Despite searching on Google, I couldn't find any information about it. There is a website that allows users to search for doctors in their area or state. It's possible that the number ...

Getting Started with NextJs and Firestore Setup

Recently, I have been incorporating Firebase into my NextJs project. I've set up a file called initFirebase.tsx for the server-side implementation. import * as Sentry from '@sentry/nextjs'; import * as admin from 'firebase-admin'; ...

Tips for storing HTML form data in a local JSON file without the need for PHP or Node.js dependencies

I'm interested in saving any information panel in an HTML file to a local JSON file. For example, if there are blocks like this: <div class="panel"> <div> <input type="text" name="producttype" id=&q ...

Loading screen for specific content within the current WordPress theme

I am trying to display a preloader only in the 'content' div, but it ends up hiding the entire page. The structure of the site is as follows: Title Menu Content (where I want the preloader) Footer I'm having trouble figuring out where exa ...

Enhancing visuals with THREE.js and the power of transparency through EffectComposer

I am attempting to blend texture passes in a way that preserves the alpha channel. I have experimented with several methods to achieve this. The renderer has the alpha property set to true. Renderer with various setClearColor settings. The material on th ...

Merge two JavaScript functions

I've been attempting to merge two if functions together but I keep encountering errors. Despite trying different methods, I have not been successful in combining them. My goal is to check if the body has a specific class and if it does, I want to unc ...

What is the best way to add an array into another array?

I am working with a main array consisting of 64 positions, and for each position, I need to create another array. For example: someArray[index] = [someObject]. How can I generate these arrays? And how can I access someObject.name and someObject.lastName f ...