The API response indicating success is simply denoted as "Success: True", without any accompanying data

I've set up my application on an express server with a proxy to communicate with the API server. Here's a snippet 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="b8cecdddf88b968c9681">[email protected]</a>/dist/vue.global.js" defer></script>
    <script src="app.js" defer></script>
  </body>
</html>

This is how my App.js is structured:

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 built on ExpressJS...

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();

// Rest of the server.js code omitted for brevity

When I run npm run start, my server.js fires up without any issues. However, when I enter a customer ID and click the "Are They Legit?" button, I only see {success: true} in the console without any response data or error indication.

I suspect the issue might be related to CORS as everything seems configured correctly. I've tried various solutions from StackOverflow and Google, but nothing has resolved it. Can someone provide guidance on resolving this issue?

Answer №1

This particular block of code will execute without any conditions, regardless of the URL being accessed:

app.use(function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Headers', 'X-Requested-With')
  res.status(200).json({ success: true}); // <============================ Important!
  next()
});

The response generated by this code may interfere with specific actions intended for the API endpoint /checkCustomer.

If you only need this response for certain URLs, consider making it conditional or adjusting your logic accordingly.


On a separate note: I am unfamiliar with the proxy middleware used here, but it appears that apiProxy should actually return the outcome of createProxyMiddleware so that it can be utilized within app.use. As it stands, the current setup does not return anything because an arrow function starting with { after => signifies a complete function body, necessitating a return statement to pass back the result from createProxyMiddleware.

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

Angular HttpClient request fails to initiate

Overview: A button click on a form triggers the methodForm within the component. methodForm then calls methodService in the service layer. methodService is supposed to make an HTTP POST request. Problem: The HTTP POST request is not being made. However, me ...

Discover the element's selector for the event that was triggered using jQuery

In the process of creating a lightweight real-time application, we are utilizing jQuery's event system to facilitate communication between modules. Any changes made in the DOM that affect elements outside the module are achieved through triggering eve ...

Unable to send information to a function (using jQuery)

I'm struggling to pass the result successfully to another function, as it keeps returning an undefined value: function tagCustomer(email, tags) { var o = new Object(); o.tags = tags; o.email = email; o.current_tags = getCustomerTags(email ...

Enhance your figures with a unique Javascript magnifying tool that works seamlessly across all browsers

After searching the web for magnifying glasses, I found that most only work for one picture. So, I took matters into my own hands and created a magnifying glass that can magnify all pictures within a specific div. It functions perfectly on Chrome browser b ...

What is the best way to prevent labels from floating to the top when in focus?

How can I prevent the label from floating on top when focusing on a date picker using Material UI? I have tried several methods but nothing seems to work. I attempted using InputLabelProps={{ shrink: false }} but it did not resolve the issue. Here is a li ...

What could be causing my second ajax call to render the page unresponsive?

I am encountering an issue with my AJAX call. It works fine on the first attempt, but when I try to call it a second time, the page becomes unresponsive. I am not sure what is causing this issue. The code is located within the document ready function. The ...

Determine whether the user has scrolled past a specific threshold

Is there a way to display the button with the id backtotop only when the user has scrolled more than 250 pixels? This is my code: <template> <div> <button v-if="checkScroll" class="goTop" @click="backToT ...

Is it possible for JavaScript to access and read a local file from a web page hosted locally

I am interested in using html, css, and javascript to develop a user interface for configuring a simulation. This interface will be used to generate a visualization of the simulation and an output parameters file based on multiple input files. It is impor ...

What is the best way to place a JavaScript or jQuery variable within an HTML tag?

Suppose we have a variable called var sticky_element = ".menu"; and then there's this line of code: jQuery(sticky_element).wrapInner('<div class="menu-inner"></div>'); How do we replace the menu in class="menu-inner" with the ...

Authorization process using access tokens in a Node.js Express application (excluding JWT or Passport)

When developing a REST API server, it is important to consider security measures for user authentication. One approach is to generate or fetch a 32-character access token from the database upon user login. The token should be sent in the header of each req ...

Converting a JavaScript variable to PHP for use with MySQL

Struggling to insert my Javascript variable "score" into a Mysql database, and it's not working as expected. Below is the code from Index.php: var score = 0; function post() { $.post('scoreadder.php',{uscore:score}, function(data){ consol ...

Prevent refreshing Google Maps when changing routes in AngularJS

Utilizing a Google map as the background for my website adds a unique visual element to the data displayed on different routes. However, I have encountered an issue where the map reloads with every route change, resulting in an unsightly flash of white tha ...

Leveraging Selenium to extract text from a dynamically populated DIV using JavaScript

I am currently utilizing Selenium to automatically retrieve all comments from a New York Times article. Once the comments are loaded, my goal is to extract them and save the information for future use. However, upon inspecting the source code of the articl ...

What is the trick to have a CSS element overflow the boundaries of its containing div entirely?

Currently, I have a JS Fiddle project where I am attempting to achieve a specific effect. In the project, there is a circle positioned at the center of a div. When the script runs, the circle expands evenly in all directions until it reaches the borders on ...

The React login form is transmitting blank information to the server

My frontend-backend setup was functioning smoothly until I decided to enhance the code quality by adding controllers. Now, whenever a user attempts to login, my backend receives an object with no data and I'm at a loss as to where the issue could be. ...

Regex produces odd results in string processing

This particular JavaScript regular expression: homework.description = (homework.input.match(/((\(((\S\s?)\)?)*)|(about( \w*)*))/i)); When applied to the text: potato (potato) Produces this unexpected output: (potato),(potato), ...

Displaying text that follows the cursor on a JavaScript mouseover event

When I hover over the pin with my cursor, the text should move along with the mouse. However, the current position of the text is off and needs to be adjusted to be next to the pin. What is a more accurate way to calculate the correct position? var toolt ...

The Json object's size increases exponentially with each subsequent return

There seems to be a strange issue with the PHP file that is causing the JSON objects to duplicate. The first time I run the script, I receive 5 rows, which matches the number of rows in the table. However, on the second run, I get double the results. Wha ...

Modifying the color of a header through clicking on a specific anchor link

My goal is to create a fixed side nav bar on my webpage with an unordered list that links down the page using anchors. In addition, I want to dynamically change the color of an h2 element based on which item in the fixed nav bar is clicked on. For instan ...

Having trouble processing a JSON object using Jquery?

Hello, I am currently working on parsing a JSON object using jQuery. So far, I have successfully extracted all the necessary information from the results except for one crucial piece - the performance tags. Each JSON result is enclosed in an event tag and ...