Express app issues error: JSON response not returned properly - Uncaught SyntaxError: Unexpected end of data

I'm in need of some fresh perspective.

My goal is to have a basic Express app return JSON data (in this case, a Firebase token) every time a request is made to it.

Here's the code for my Express server:

app.get('/validate', function (req, res) {
  var customToken = firebase.auth().createCustomToken(req.query.token);
  res.json({
    token: customToken
  });
});

app.listen(8000, function () {
  console.log('Listening on port 8000');
});

This is how the client sends a request (running on port 3000):

export function login() {
    return fetch('http://localhost:8000/validate?token=666', {
      method: 'GET',
      mode: 'no-cors',
      headers: new Headers({
          'Authorization': apiClient.headers.Authorization,
          'Content-Type': 'application/json'
        })
      })
      .then(response => console.log('RESPONSE: ', response.json()))
      .catch(response => console.error('ERROR: ', response));
  }

The Express app seems to be functioning correctly as I can view the necessary JSON when I visit

http://localhost:8000/validate?token=666
in a browser.

However, upon making the client request, I encounter the following error:

Uncaught (in promise) SyntaxError: Unexpected end of input

and the Response log displays like this:

RESPONSE:  Promise {[[PromiseStatus]]: "rejected", [[PromiseValue]]: SyntaxError: Unexpected end of input↵    at SyntaxError (native)↵    at eval (eval at <anonymous> (h…}__proto__: Promise[[PromiseStatus]]: "rejected"[[PromiseValue]]: SyntaxError: Unexpected end of input↵    at SyntaxError (native)↵    at eval (eval at <anonymous> (http://localhost:3000/main.js:1381:2), <anonymous>:78:42)message: "Unexpected end of input"stack: "SyntaxError: Unexpected end of input↵    at SyntaxError (native)↵    at eval (eval at <anonymous> (http://localhost:3000/main.js:1381:2), <anonymous>:78:42)"get stack: stack()set stack: stack()__proto__: Error
login.js?b88c:54

If you have any insights on what mistake I might be making, I would greatly appreciate it.

Answer №1

After encountering a similar issue, I dug deep and discovered that the presence of { mode: 'no-cors' } is specifically for handling opaque responses that cannot be accessed directly. In order to retrieve the response, it must be cached using the Cache API, which can later be retrieved with the help of a service worker.

To resolve this problem, I took the route of adding the Access-Control-Allow-Origin: * header to my server-side configuration (ensuring its security in a production environment and confirming that only authorized requests are being made to my server) while also eliminating the mode:'no-cors' option from the request.

Answer №2

If anyone is looking for a solution, I managed to resolve my problem by including the following code snippet in the server-side script:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

This addition proved to be effective in solving the issue.

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

Tips for changing a specific item within an ng-repeat loop in AngularJS

Here is my HTML code: <tr ng-repeat="customer in customers"> <td> {{customer.customer_name}} </td> <td> {{customer.mobile}} </td> </tr> Upon executing this code, I receive 3 <tr>...</tr> blocks as s ...

The Power of Asynchronous Programming with Node.js and Typescript's Async

I need to obtain an authentication token from an API and then save that token for use in future API calls. This code snippet is used to fetch the token: const getToken = async (): Promise<string | void> => { const response = await fetch(&apos ...

Incorporate a line break between the day and month on your JQuery datepicker

Is it possible to insert a line break or some other element between the day and month in the input field when using JQuery datepicker? Here is the current code I have: jQuery('#checkin').datepicker({ showAnim: "drop", dateFormat ...

encounter an auth/argument issue while using next-firebase-auth

Issues: Encountered an error while attempting to log in using Firebase Authentication. No errors occur when using the Firebase Auth emulator, but encountered errors without it. Received a 500 response from login API endpoint: {"error":"Unex ...

Crafting a dynamic bar chart with recharts for your data visualization

Is it possible to set a custom bar range in the Bar Chart made with recharts? Can we define specific start and end positions for the bars? For instance, if I have two values startPos and endPos, is there a way to create a Bar that starts at startPos and e ...

Issue: Unable to locate 'path' in directory 'C:workdemo ode_modulesmime-types'

Encountering an error after updating from "react-scripts": "4.0.3" to "react-scripts": "5.0.1",. I need assistance with understanding why this error is occurring and how to resolve it... ERROR in ./node_modules/mime ...

Update the numerical data within a td element using jQuery

Is there a way to use jquery to increase numerical values in a <td> element? I've attempted the following method without success. My goal is to update the value of the td cell by clicking a button with the ID "#increaseNum". Here is the HTML st ...

Tips for preventing the creation of duplicate arrays when using JSON Deserialization alongside a sophisticated Factory Pattern

Currently, I am engrossed in a thrilling side project involving the creation of a text-based adventure game and engine. My goal is to have most of the game's content written in JSON format. These JSON files will be used to populate a series of factori ...

Implementing Vue.js click event behavior on a component within the template

Encountering an issue while developing Vue's template onclick event. Trying to open a module when clicking a file, I have looked at some samples with native code, but it does not quite fit into my code and I cannot reach the console. Here is my code: ...

What methods are most effective when utilizing imports to bring in components?

Efficiency in Component Imports --Today, let's delve into the topic of efficiency when importing components. Let's compare 2 methods of importing components: Method 1: import { Accordion, Button, Modal } from 'react-bootstrap'; Meth ...

How can I insert my URL into the webPDFLoader feature of LangChain platform?

I need help figuring out how to load a PDF from a URL using the webPDFLoader. Can someone explain how to implement this? Any assistance would be greatly appreciated. I am working on this task in nextjs. Where should I place the pdfUrl variable within the ...

When working with NodeJS, Express, and MySQL, it is important to avoid setting headers after they have already been sent

I am working on a NodeJS application using Express and here is the relevant code snippet. app.post('/open', checkStatus, function(req, res) { if (req.error) { console.log(req.log); return res.json(req.error); } console.log(current ...

Choosing a random JSON object using jQuery

My jQuery script is designed to display the content from a JSON file when the page loads... $.getJSON('b.json', function(data) { $('#dictionary').empty().hide(); $.each(data, function(entryIndex, entry) { var html ...

Instant urban locator

Is there a way to automatically populate the visitor's city in the membership form? Member Register Form Name: Emre Email:--- Pass:--- City: Istanbul // Automatically detected location How can I implement automatic location detection for the ...

Creating a resilient node websocket client with enhanced security (overcoming the challenge of verifying the initial certificate)

What's Working? I successfully created a node server using WebSocket technology. I used the library WebSocket-Node and added key/cert to my HTTPS/secure websocket server as shown below: import WebSockerServer from "websocket"; import fs fro ...

The toggler in Bootstrap 5's Navbar menu is experiencing difficulties opening on mobile browsers

Just arrived here for the first time. Encountering an issue with my Bootstrap 5.1 Navbar menu. Background info: My website is hosted locally via Xampp with php pages for forms and cookies. Everything functions perfectly on desktop. Checked responsiveness o ...

Troubles encountered when using AJAX to send a JSON Array to a PHP script

Hey there, I'm just starting to explore the world of ajax and json. So I decided to test out some sample code before diving into my project. However, I've hit a roadblock when trying to send information to my PHP file. Even though I've caref ...

Angular 2 Express failing to trigger ngOnInit method

I'm having some trouble with Angular services. I used the default code from "Angular.io" to make service calls, but for some reason the ngOninit method isn't getting called. I've implemented the component from OnInit and added @Injectable to ...

Find out which way the user is scrolling in your React js application

I'm struggling to determine whether the scroll event is moving up or down, and I haven't been able to find a solution yet. import React, { useState, useEffect } from "react"; import { Link } from "react-router-dom"; const Nav ...

"Enhanced jQuery confirmation dialog plugin with full screen functionality and automatic

My current web-based production tracking system isn't getting the attention it needs from users, so I'm in the process of creating a full-screen alert and confirm function to ensure they pay closer attention. The idea is for alerts to remain on t ...