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

Creating a modular mongoose connection in a Node.js application

For my project, I am planning to create a standalone module named connection.js to establish a Mongoose connection. var mongoose = require('mongoose'); mongoose.connect('mongodb://host:port/db'); mongoose.connec ...

Display an array containing date objects in a dropdown menu for users to select from

I am working with an API call that returns an array of objects. Each object in the array contains a date or timestamp in ISO format. Right after my render() method, I have the following code snippet: const pickerItems = this.props.currentData.trips.map(t ...

Exploring connections among Array Objects on a Map

Here are some JSON examples of Pokemon Battles: [ { "battleID": "1", "trainers": [ { "LastName": "Ketchum", "ForeName": "Ash" }, { "LastName": "Mason", ...

Include a photo in the notification when utilizing the sendToTopic function

I am looking to utilize the sendToTopic method for sending notifications to a topic. Is there a way to include an image in the notification? It seems that notification.imageUrl is not available as an option. ...

Why does the getOwnPropertyDescriptor() method in JavaScript include custom properties that are inherited?

As I delve into the world of JavaScript and Node.js, a question has arisen regarding the Object.getOwnPropertyDescriptor() function. Let's explore the following snippet of code: var rectangle = { width: 10, height: 5, get area() { ...

Utilizing local storage, store and access user's preferred layout options through a click function

Exploring the realm of localstorage for the first time, I am considering its use to store a specific ID or CLASS from my css file. This stored information would then be utilized to render a selected layout (grid/list) in the user's browser upon their ...

Tips for sending functions from client to server in Node.js

I'm working with this code snippet: const http = require('http'); const fs = require('fs'); const handleRequest = (request, response) => { response.writeHead(200, { 'Content-Type': 'text/html' ...

What is the correct way to serialize and deserialize an array of objects to and from JSON format?

I'm currently working on implementing a friends list feature that needs to be stored in a .json file using Kotlin/Java with libgdx. While Java is also an option for this project. The code I have written for (1) isn't functioning correctly, so ins ...

Is there a scenario where an object exists that is not comparable using deepStrictEqual or notDeepStrictEqual

During my testing of the REST API using supertest along with mocha and standard assert, I encountered an issue where both test cases were returning false. Interestingly, Mongo is also throwing an error which might explain why at least one case would fail ...

Using Regular Expressions in Javascript

I have gone through numerous posts with this title, but so far, none of them have addressed my specific query... My requirement is to utilize regex in the following format: "/^ user provided input $/i". The user can include the special regex character * e ...

React.js Component Composition Problem

I am attempting to replicate the following straightforward HTML code within a React environment: Traditional HTML <div> Hello <div>child</div> <div>child</div> <div>child</div> </div> React(working ...

Controlling data tables with knockout.js

I have successfully integrated an API in knockout.js, but I am facing an issue with displaying the amount based on accounting principles. My table definition includes columns for id, name, debit, credit, and amount. Since not all amounts fall under debit o ...

Responsive design involves ensuring that web elements such as divs are properly aligned

I am currently working on aligning 2 divs in a specific way that is responsive. I would like the right div to stack on top of the left div when the screen width reaches a certain point, as opposed to them both taking up 50% of the container's width. ...

A glitch in the system is causing the postman to throw a 500 internal server error without providing any details when attempting

I'm currently developing an app that helps users create and manage menus. However, when I send a post request to add a menu in Postman, I receive a blank message along with a 500 internal server error. The request I'm making meets the model requi ...

preserving the status of checkboxes based on an array of binary values

I am trying to figure out how to restore the state of checkboxes in an ORACLE APEX tabular form. The selection is made in the first column using the APEX row selector f01. After saving the checkbox state in a collection and then transferring it to an arra ...

Use the Fetch() function in Google Sheets to parse JSON data and organize it into

I have been attempting to utilize the Fetch() function in order to import a json file and populate multiple Google sheets. However, I have encountered some difficulties as my current knowledge is insufficient. The json file I am working with is constantly ...

Receiving an error message stating "The JSON value could not be converted to System.Int32" when attempting to post JSON data via AJAX to a Web API

I need to transfer information from my website to a WEB API that my partners are developing via AJAX. This WEB API is built on a .net Core 3.0 application, and the purpose is to register new users. However, I am encountering an issue with parsing the inpu ...

An error stating that "DataTable is not a recognized function" occurred within the document function

Previously, I set up datatables using the code below: $(function () { $('#keywords-table').DataTable({ "ajax": ({ url: "{{ route('getKeywordsByProductId') }}", method: "get", ...

Navigating through each segment

I'm currently working on a website with sections that are set to be 100% height of the window, but at least 800px tall. My goal is to implement a smooth scrolling functionality where one scroll moves the view from section to section. However, if the ...

Exploring the effectiveness of React Hook Form using React Testing Library

My Component includes a form that, upon submission, utilizes Apollo's useLazyQuery to fetch data based on the form values. The form in the component is managed by React Hook Forms, with the handleSubmit controlled by RHF. <FormContainer onSubmit= ...