1

Brand new to express and relatively inexperienced with JS/TS. Playing around with setting up an express server with two endpoints.The response from httpbin (https://httpbin.org/get -> http://localhost:3031/simpleget) appears fine.

However, I cannot seem to ungarble JSON that comes from http://jsonplaceholder.typicode.com/users/1 ( http://localhost:3031/users/1 ) . The response looks something like:

"��\u000f\u0000 ���w����?JO�_��9��\u0013U>H�z\u000b�]{�\u0014�)�o6Ī\u0004��pc]+ܜ��Dž\u0006�g�Gg\u000f [�\u001aэ\u0007����\u001a�)<\f�\u0017�{���DK��ʌ�ҳ�h\rz�hS�'�����Nu\u0007��5�v\u0001r��̴\u0006},\u001d;|ںY�\u0003�\u0016;�dw��#�r�dk�#�A/{\u00196��K�$;�i;V��U�Z�&)�4m-#=\u0001�q$&)�$�V\f\u0002����5���(]�\u0004��\u0003��wS3\u000e$��\u0014Eh�$7e�D8dy��:�΅�i\rjlWI�Z���\u0015���O<\u001c�\u00007g�c��"��AǁU!\r���F�q~-�lM�GQ��\u0001k�Dw�\u0018dQ�� N�Sr�:�sP��̶\u0017���\u001e9�w\u0005"

Tried textdecoder, json stringify, unicode conversion and many other approaches but nothing seems

const express = require("express")
const axios = require("axios")
const cors = require("cors")

const app = express()
app.use(express.urlencoded({ extended:true}))
app.use(cors())

app.get("/users/:id", async(req, res) => {
    const { data } = await axios.get(
        `https://jsonplaceholder.typicode.com/users/${req.params.id}`
        )
    res.json(data)
})

app.get("/simpleget", async(req, res) => {
    const {data} = await axios.get("https://httpbin.org/get")
    res.json(data)
})

app.listen(3031)

What am I doing wrong?

Spade
  • 2,220
  • 1
  • 19
  • 29
  • 1
    Have you looked at the headers in the response, for something like accept-encoding? – Jon Skeet Nov 23 '22 at 21:15
  • @JonSkeet I see `vary: 'Origin, Accept-Encoding', 'access-control-allow-credentials': 'true', 'cache-control': 'max-age=43200',` in the response header. How do I deal with it? – Spade Nov 23 '22 at 21:33
  • This is definitely an encoding issue. Try this: https://stackoverflow.com/a/21284905/4088472 – Slava Knyazev Nov 23 '22 at 21:44

1 Answers1

1

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

The default of it is gzip

This is demo code.

const express = require("express")
const axios = require("axios")
const cors = require("cors")

const app = express()
app.use(express.urlencoded({ extended: true }))
app.use(cors())

app.get("/users/:id", async (req, res) => {
    const { data } = await axios.get(
        `https://jsonplaceholder.typicode.com/users/${req.params.id}`,
        {
            headers: {
                'Accept-Encoding': 'application/json',
            }
        }
    )
    res.json(data)
})

app.get("/simpleget", async (req, res) => {
    const { data } = await axios.get("https://httpbin.org/get")
    res.json(data)
})

app.listen(3031)

Install

npm install express axios cors

Run it

node users.js

Result if browser open server

http://localhost:3031/users/1

enter image description here

Bench Vue
  • 5,257
  • 2
  • 10
  • 14