Home > Net >  Using axios inside an express route is returning special characters instead of json in data field
Using axios inside an express route is returning special characters instead of json in data field

Time:12-01

I have been trying to fix this issue for a pretty long time, I would appreciate the help.

I have tried using the nodeJs library of Moralis it worked on my local but did not on dev server was returning undefined, so I came back to axios;

I tried changing header type.

Tried using .send instead of .json

Tried puting the response in status(200)

Tried sending it as full response

Console.log(response) has the same result from the terminal


This is the route and the axios inside

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

And this is the result Im getting

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\x06���6F@\rZb\x02�6\x03*�\x109\x05rJ�g\x15�M�f�٤\x1C�1��U�\x7FmCi~�MY\x15Vw����n�oC���k��6-6=���X�\x06;��\x0B��cu�-�����\x04y��Y\x02\x10�\x04��a\n'  
    "\\\x07��'��]�_�\x16i�N��r>\x1D�����n\x18�-���/J\x13�O�\x04Dc\x1D\x00�L�8�*ȔT��t\x16d�I��L\x16�]\ru�����_e�R\t1��\f�;�5D�*��$\r�\x1C�p|Pv�m�\x17|\x1E}\x16�����R�\x14F\x1B�\x11�z����\x1D\x00\x00��\x03\x00R\x1A9!�\x02\x00\x00

When I use the same function in my client, it works like a charm, that`s why I think this is about Express or body-parser, any other endpoint in my app which doesn't use axios works fine.

This is the express.ts

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

And this is the 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);
}

CodePudding user response:

You need to add Accept-Encoding with application/json in axios.get header.

It is known defect.

The default of it is gzip in axios v1.2.0

using this option for axios get call

    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,
        }
    };
  • Related