When incorporating axios within an express route, it is causing the data field to display unusual characters instead of JSON

I've been grappling with this issue for quite some time now, and any assistance would be greatly appreciated.

Initially, I attempted to resolve the problem by utilizing the Moralis nodeJs library. While it worked fine on my local environment, it returned undefined on the development server. Consequently, I switched back to using axios;

I experimented with altering the header type.

I also tried substituting .send for .json

I attempted setting the response in status(200)

I even tried sending it as a full response

The result shown from console.log(response) was consistent across the board


This snippet showcases the route and corresponding axios implementation

import express from "express";
import axios from 'axios';
import { chainIdAliases, wrappedNatives } from "../constants";
import { envVars } from "../server";

const moralis = express.Router();

moralis.get('/get_user_tokens/', (req, res): any => {
    const { address, chainId }: any = req.query
    const options = {
        method: 'GET',
        url: `https://deep-index.moralis.io/api/v2/${address}/erc20`,
        params: { chain: chainIdAliases[chainId] },
        headers: { accept: 'application/json', 'X-API-Key': envVars.MORALIS }
    };
    axios.request(options)
        .then((response) => {
            res.status(200).json(response.data)
        }).catch((error) => {
            res.status(400).json(error);
        });
});


export default moralis

This is the unexpected output I'm encountering

data: '\x1F�\b\x00\x00\x00\x00\x00\x00\x03��OK\x031\x10��RrRXJ�N�=�B�"BۓL&I[��H�Ŋ����t\n' +
    '9\x0E��{��v)u\x18�6�=\x19?P���6F@\rZb\x02�6\x03*��9: �5D�*��$\r\x1Cp|Pv�m�|\x1E}�R\x14F\x1B�\x11z���\x1D\x00��\x03\x00R\x1A9!��'

Interestingly, when employing the same function within my client, everything runs smoothly. This leads me to believe that the issue lies with Express or body-parser, as other endpoints in my application not utilizing axios are functioning as expected.

Here's an overview of the express.ts file

import bodyParser from "body-parser";
import express from "express";
import helmet from "helmet";
import morgan from "morgan";

// Routes
import moralis from "./routes/moralis";
import receipts from "./routes/receipts";

const init = () => {
    //initialize app
    const app = express();
    // adding Helmet to enhance your API's security
    app.use(helmet());
    // Bodyparser middleware
    app.use(bodyParser.json());
    // adding morgan to log HTTP requests
    app.use(morgan('dev'));
    // Routes
    app.use("/api/receipts", receipts);
    app.use("/api/moralis", moralis);
    return app;
};

export default init

Lastly, let's examine the contents of server.ts

import { createServer } from "http";
import mongoose from "mongoose";
import { Server } from 'socket.io';
import init from './express';
import dotenv from "dotenv"; 

dotenv.config()
// Export Env Vars
export const envVars = {
  MORALIS: process.env.MORALIS_API_SECRET
}
//Init Server
const server = createServer(init());
//establish socket.io connection
const io = new Server(server);
io.of('/socket').on('connection', (socket) => {
  console.log('socket.io: User connected: ', socket.id);

  socket.on('disconnect', () => {
    console.log('socket.io: User disconnected: ', socket.id);
  });
});
//Port Config
const port = process.env.NODE_ENV === 'dev' ? 5000 : process.env.PORT;
//start the server
server.listen(port, () => {
  console.log(`Server up and running at port ${port} !`);
});
// DB Config
const db = process.env.MONGO_URI as string;
// Connect to MongoDB
mongoose.connect(db, {});
const connection = mongoose.connection;
connection.once('open', () => {
  console.log('MongoDB successfully connected')
  console.log('Setting change streams');
  //Listen to new Receipts
  const receiptsChangeStream = connection.collection('receipts').watch();
  receiptsChangeStream.on('change', (change: any) => {
    const { from, to, txHash } = change.fullDocument
    switch (change.operationType) {
      case 'insert':
        io.of('/socket').emit('newReceipt', { from, to, txHash });
        break;
    }
  });
});
connection.on('error', (error) => console.log('Error: ' + error));
//On New Pending Receipt
export const emitPending = (newPending: any) => {
  io.of('/socket').emit('newPending', newPending);
}

Answer №1

Fixed the Bug in Version 1.2.1

To resolve the issue, make sure to include Accept-Encoding with application/json in the axios.get header.

This is a known defect that has been addressed.

The default setting was set to gzip in axios version 1.2.0

When making an axios get call, use the following option:

    const options = {
        method: 'GET',
        url: `https://deep-index.moralis.io/api/v2/${address}/erc20`,
        params: { chain: chainIdAliases[chainId] },
        headers: {
              accept: 'application/json',
              'Accept-Encoding': 'application/json',
             'X-API-Key': envVars.MORALIS,
        }
    };

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 buffered transformation stream in practice

In my current project, I am exploring the use of the latest Node.js streams API to create a stream that buffers a specific amount of data. This buffer should be automatically flushed when the stream is piped to another stream or when it emits `readable` ev ...

JavaScript and JSON interchangeably, the first AJAX response should be rewritten by the second response

I am facing an issue with my code: I have two ajax calls being made on window.load, and it seems like the response from the second AJAX call is overwriting the response from the first one before my function can process it. I'm not sure where I'm ...

Error: Unsupported Media Type when attempting to send JSON data from an AngularJS frontend to a Spring controller

Below is the controller function code snippet @RequestMapping(value = "/logInChecker", method = RequestMethod.POST, consumes = {"application/json"}) public @ResponseBody String logInCheckerFn(@RequestBody UserLogData userLogData){ Integer user ...

How to access additional legend labels in c3.js or billboard.js using JSON data?

I'm working with the following code snippet: ... normen is my json object .... $.each(normen, function(item) { chartX.push(this.feed_day) chartY.push(this.weight) }); createChart(char ...

Tips for verifying elements using the Loop technique in a JSON array

I am new to JavaScript and I have been trying to run the following code with an expected result like this: [["00:04:12","05:54:46"],["06:06:42","12:45:22"],["12:51:11","15:56:11"]] However, my script is not working as expected. Can someone please help ...

Utilize recursive and for loop methods for parsing JSON efficiently

I have a JSON file that requires parsing. I'm attempting to implement a recursive method for this task. The current JSON data is structured as shown below: Item 01 SubItem 01 InnerSubItem 01 Item 02 SubItem 01 InnerSubItem 01 Unfortunately, t ...

Dealing with error management in Transfer-Encoding chunked HTTP requests using express and axios

My current challenge involves fetching a large amount of data from a database in JavaScript using streaming to avoid loading all the data into memory at once. I am utilizing express as my server and a nodeJS client that retrieves the data using Axios. Whil ...

Utilizing Axios for Vue Multiselect on select/enter Event

I have successfully implemented a Vue Multiselect feature that retrieves options from my database using an axios call. This functionality works great as it allows users to select existing options or add new ones to create tags. While this setup is working ...

Error: Unable to encode data into JSON format encountered while using Firebase serverless functions

I am currently working on deploying an API for my application. However, when using the following code snippet, I encountered an unhandled error stating "Error: Data cannot be encoded in JSON." const functions = require("firebase-functions"); const axios = ...

Harnessing the Power of Google Apps Scripts: Mastering the Art of Handling Comma-Separated Spreadsheet Values Transformed

I have a spreadsheet where column 1 contains source file IDs, with each cell holding only one ID. Column 2 has destination file IDs, where cells contain multiple IDs separated by commas. I utilize a script to retrieve these values and perform various opera ...

JS/Apps Script: Passing object and its keys as function parameters

When working with Google Apps Script, I have a specific task that involves looping through data and writing only certain keys to a sheet. I want this looping operation to be done in a separate function rather than directly in the main function, as it will ...

Stopping unauthorized users from manipulating REST URLs

I am currently exploring methods to prevent an exploit where a user manipulates the URL, specifically in a GET request scenario. The following code represents a route on my Express router that processes incoming requests for a certain collection "A" and re ...

KeyBy lodash method stores values in an object using the specified property as keys

There are multiple items stored in an array: "objects": [ { "category": "XXXXX", "item_name": "over_pkg_0", "price": 230 }, { "category": "XXXXX", "item_name": "over_pkg_1", "price": 54 }, ...

Step-by-step guide for launching a Next.js/Node application

Currently, I am developing a full-stack project utilizing a next.js application for the front-end and a node/express server for the API. The front-end and back-end are running on separate ports. Here is how my application is configured: https://i.stack.im ...

Creating a line chart with multiple axes using Chart.js by importing data from a Google Sheet in JSON format

My attempt to visualize the data stored in a Google Sheet using Chart.js resulted in a multi-axis line chart. The data I have looks like this: https://i.stack.imgur.com/F8lC7.png When trying out the following code, I encountered an issue where only the f ...

What are the steps to create a JSON file structured in a tree format?

Can you provide instructions on creating a JSON file in the following tree format? root child1 child11 child2 child21 child22 child3 child31 I am looking to generate a sample JSON file that adheres to the ...

use the fetch api to send a url variable

I'm struggling to pass a URL variable through the API fetch and I can't seem to retrieve any results. As a newcomer to Javascript, any help is greatly appreciated. //Get IP address fetch('https://extreme-ip-lookup.com/json/') .then(( ...

Every time I attempt to execute this piece of code in "node.js", an error pops up

const express = require('express'); const request = require('request'); const bodyParser = require('body-parser'); const https = require('https'); const app = express(); app.use(express.static('public')); ...

Insert an element into a JSON collection

I am currently working on a JavaScript function that utilizes an ajax call to retrieve data from an API in the form of a JSON array. Here is a snippet of the array structure that I receive: [ { "ErrorType": "Errors", "Explanations": [ { ...

Tips for effectively parsing extensive nested JSON structures?

JSON Data on PasteBin I need assistance in converting this JSON data into an Object. It seems valid according to jsonlint, but I'm encountering issues with parsing it. Any help would be greatly appreciated. "Data":[{...},{...},] // structured like t ...