Fetching requests always seem to remain unfinished

I previously had this code in a different question, but since they are not unrelated, I decided to move it to a new one...

Here I am again with the same code, but facing a different issue. My application is set up and running on an express server with a proxy to communicate with the API server. Below is an outline of my code:

HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <link rel="icon" href="/favicon.ico">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Is That Legit?</title>
    <link rel="stylesheet" href="assets/main.css">
  </head>
  <body>
    <div id="app">
      <div class="wrapper">
        <header>
          <img alt="Site logo" class="logo" src="assets/logo.svg" width="333" height="187" />
        </header>
        <h1 class="app-title">Is User Legit</h1>
        <input @input="saveID" placeholder="User ID" />
        <button @click="checkID">Check Customer is Legit</button>
      </div>
    </div>
    <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4e383b2b0e7d607a6077">[email protected]</a>/dist/vue.global.js" defer></script>
    <script src="app.js" defer></script>
  </body>
</html>

My App.js follows a fairly standard setup like this:

const app = Vue.createApp({
  data() {
    return {
      customerID: ''
    }
  },
  methods: {
    saveID(event) {
      this.customerID = event.target.value;
    },
    async checkID() {
      const options = {
        method: 'GET',
        headers: {
          Accept: 'application/json',
          'x-api-key': 'ThisIsMyAPIKeyThereIsNoOtherLikeIt'
        }
      }
      const url = `/checkCustomer?customerNumber=${this.customerID}`;
      try {
        const result = await fetch(url, options);
        const json = await result.json();
        console.log(json);
      } catch (error) {
        console.error(error);
      }
    },
  }
})

app.mount('#app')

Below is my server.js file (powered by ExpressJS) as well...

const express = require('express');
const https = require('https');
const cors = require('cors');
const { createProxyMiddleware } = require('http-proxy-middleware');
const fs = require('fs');
const app = express();

// app.use(cors());
app.use(express.static('dist'));
app.use('/dist', (req, res) => {
    res.sendFile(__dirname + 'dist/index.html');
});
app.use('/dist/assets/main.css', (req, res) => {
    res.sendFile(__dirname + 'dist/assets/main.css');
});
app.use(express.json());
app.use(
  cors({
    origin: ['https://myAPI.com'],
    methods: ['GET', 'POST', 'PUT', 'DELETE'],
    allowedHeaders: ['Content-Type', 'Authorization'],
  })
);
app.use(function (req, res) {
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Headers', 'X-Requested-With')
});

// Add middleware for http proxy
const options = {
    target: 'https://myAPI.com', // target host
    pathRewrite: {
        '^/checkCustomer' : ''
    },
    router: {
        'localhost:3000': 'https://myAPI.com',
    },
};
const apiProxy = (req, res) => {
    createProxyMiddleware(options);
}
app.use('/checkCustomer', apiProxy);

https.createServer(
    {
        key: fs.readFileSync("thisIsMyServerKey.key"),
        cert: fs.readFileSync("thisIsMyServerCert.cert"),
    },
    app
).listen(3000, () => {
    console.log('Listening on: https://localhost:3000');
});

When I run npm run start to start my server.js, there doesn't seem to be any issues. The goal is to enter a customer ID in the input box and click the "Are They Legit?" button to verify if a customer is legitimate or not. The proxy steps in to check the /checkCustomer endpoint, remove that part, append the rest of the URL to the API URL, and submit the request.

However, it seems that the request never completes as expected.

The current configuration is set up to address CORS-related problems.

I have tried looking through articles, questions on StackOverflow, and other solutions from Google, but none have provided the desired outcome so far. This attempt has been the closest to resolving the issue. Could someone provide guidance on how to fix this?

Answer №1

After successfully refactoring this in vite, everything seems to be working smoothly. Check out my vite configuration below:

import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import VueDevTools from 'vite-plugin-vue-devtools'

// Vite configuration
export default defineConfig({
  plugins: [vue(), VueDevTools()],
  server: {
    proxy: {
      '/checkUserIsValid': {
        target: 'https://linkToMyAPIServer/URL/for/QUERY',
        changeOrigin: true,
        secure: false,
        rewrite: (path) => path.replace(/^\/checkUserIsValid/, '')
      },
      cors: false
    }
  },
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  }
})

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

Merging an AppBar and Drawer in Material UI for a seamless user interface design

I am working on integrating an AppBar component with a drawer feature. Here is the code for the AppBar: import React from "react"; import PropTypes from "prop-types"; import { withStyles } from "material-ui/styles"; import AppBar from "material-ui/AppBar" ...

"Unable to move past the initial segment due to an ongoing

My portfolio webpage includes a "blob" and "blur" effect inspired by this YouTube video (https://www.youtube.com/watch?v=kySGqoU7X-s&t=46s). However, I am encountering an issue where the effect is only displayed in the first section of the page. Even a ...

The problem with utilizing the Node `util.inherits` method

I have encountered an issue with a 'this problem' in a Node server. It seems that replacing worker.stuff with worker.stuff.bind(worker) is necessary for it to function correctly. Is there a way to incorporate the bind method into the Worker Clas ...

Ensure the form is properly validated before initiating the submission process on 2checkout

Attempting to prevent the form from being submitted, I implemented the code below. Typically, this method works perfectly fine. However, when integrating 2checkout js (), it does not function as intended. <form onSubmit="validate(); return false;" meth ...

"Eliminate any inline styling from a string element with the power of JavaScript/j

If I have the following string: let sentence = '<h1 style="lots of class"> </h1><h2> <p style="bunch of class"> </p> <p style="bunch of class"> </p></h2>'; This string contains multiple elements a ...

Bring in Bootstrap and the Carousel plugin using Webpack Encore

Currently, I am tackling an issue within my Symfony project that involves Webpack Encore and the loading of Bootstrap and the Carousel plugin. The problem may stem from how I import Bootstrap, as it seems to partially work when I import the file like this ...

What causes the menu icon to shift to the left upon clicking it?

I'm currently working on a website project that involves implementing a fixed navbar with jQuery sliding animation for the menu. However, I've encountered an issue where the "menu_icon" is getting pushed to the left every time the menu slides dow ...

Utilizing the Google Translate API within an ASP MVC framework to translate a div's content from English to Arabic

Currently, I am working on a small project that involves two divs: one for English and another for Arabic. Despite creating the project, I am encountering an issue with getting the translation from English to Arabic. Below is the code I have attempted, but ...

The attribute 'selectionStart' is not a valid property for the type 'EventTarget'

I'm currently utilizing the selectionStart and selectionEnd properties to determine the beginning and ending points of a text selection. Check out the code here: https://codesandbox.io/s/busy-gareth-mr04o Nevertheless, I am facing difficulties in id ...

Loading texts with the same color code via ajax will reveal there are differences among them

I am currently designing a webshop with green as the primary color scheme. Everything is functioning perfectly, but I have noticed that the text within an ajax loaded div appears brighter than it should be. The text that loads traditionally is noticeably d ...

Having trouble with Angular UI Select functionality?

I have integrated the angular ui select library from https://github.com/angular-ui/ui-select into my project. Instead of using the traditional select element, I am now utilizing the ui-select directive. This is a snippet of my code: <select class=" ...

Efficiently Loading AJAX URLs using jQuery in Firefox

setInterval(function(){ if(current_url == ''){ window.location.hash = '#!/home'; current_url = window.location.hash.href; } else if(current_url !== window.location){ change_page(window.location.hash.split('#!/&apo ...

Tips for circumventing the ajax data size restriction in asp.net mvc3

Currently, I am implementing an auto suggest function using AJAX in the following manner: $("#empName2").autocomplete({ search: function (event, ui) { var key = CheckBrowser(event); if (key == 13) return tr ...

When toggling between light and dark themes using the useMediaQuery hook, the Material-ui styling is being overridden

While working with next.js and material-ui, I encountered an issue where the theme would change based on user preference. However, when switching to light mode, the JSS Styles that I had set were being overwritten. This problem only seemed to occur in ligh ...

What is the process for implementing the sticky table header jQuery plugin?

I am looking to implement a sticky header on all tables in my web application, which is built on PHP. As the amount of data continues to grow, search results are fetching more records that may not be visible. I am primarily a PHP programmer and do not have ...

Is there a way to sort through objects in a JSON file using two shared values? Specifically, I'm looking to filter the JSON objects based on both common x and y values

Given a JSON file, I am looking to group objects based on common x and y values. Essentially, I want to group together objects that share the same x and y properties. Here is an example of the JSON data: let data = [{ "x": "0", "y& ...

How to get an empty object as a response in a NODE.JS request?

For some reason, I am attempting to send an object to my backend. Even though I can retrieve valuable information from my network's payload, my req.body consistently returns an empty object. View my issue ...

Obtain the complete file path using JavaScript

Imagine you have a web application utilizing NodeJS and ReactJS, both working on your local machine. In this setup, NodeJS is capable of accepting files selected from the ReactJS GUI via a simple file upload feature, like so: <input type="file" id="fil ...

Real-time updates for UI data in Next.js Firestore are not being reflected

I'm currently working on implementing real-time changes using nextjs and Firebase Firestore. However, I've noticed that I still need to refresh the page in order for the updates to be visible. const [getUsers, setUsers] = useState(""); const che ...

Having trouble with the functionality of a simple jQuery toggle menu on mobile?

I am experiencing an issue with a simple toggle menu that utilizes jQuery's on: tap feature, but it is not functioning as expected: <nav id="mobile-nav"> <ul> <li>Item 1</li> <li>Item 2</li> ...