0

Working on Telegram bot. A user sends requests from the bot to an external website API to get information. The very usual stuff.

I'm trying to make a POST request from NodeJS (Express) backend which contains cyrillic symbols https://somewebsite.ru/api/v1/order.json?orderId=**МУЗ**008134

it says: TypeError [ERR_UNESCAPED_CHARACTERS]: Request path contains unescaped characters

Then I was trying to use ${encodeURIComponent(orderNumber)} instead of ${orderNumber} Error checnged to FetchError: invalid json response body at https://somewebsite.ru/api/v1/order.json?orderId=%D0%9C%D0%A3%D0%97008058 reason: Unexpected end of JSON input

When I use Postman there is no problem. I just put the whole URL https://somewebsite.ru/api/v1/order.json?orderId=МУЗ008134 and it works fine.

the server has utf8 encoding. I'm using WebStorm and VS Code - both are set with UTF8

Here is the code:

oneOrder: async (orderNumber) => {
    try {
        let url = `https://somewebsite.ru/api/v1/order.json?orderId=${orderNumber}`
        return fetch(url, {
            method: 'post',
            headers: { 'Content-Type': 'text/plain; charset=utf-8' }
        })
        .then(res => res.json())
        .then(answer => {
            if (answer.error) {
                return answer.message
            } else if (answer.orderId) {
                return `Номер заказа: ${answer['orderId']}\nСоздан ${answer['createdAt']}\nОбщая стоимость товаров в заказе: ${answer['totalCost']}\nСтатус оплаты: ${answer['status']['payment']}\nСтатус доставки: ${answer['status']['delivey']}`
            }
            return 'Нет информации по заказу'
        })

    } catch (e) {
        console.log('ERROR with oneOrder function:', e)
    }
},

...and, by the way, I have no idea why the "МУЗ008134" is not showed as a part of URL, but as a ppendix to the URL.

Thanks a lot and sorry if it seems to be too obvious.

Art Bu
  • 61
  • 6
  • I think your first error has to do with not using URL safe characters. https://stackoverflow.com/questions/695438/what-are-the-safe-characters-for-making-urls Your second error is most likely caused by calling `response.json` on a non-JSON response value. – dlaub3 Jan 28 '21 at 13:26
  • thanks! The problem is that I need to use UNsafe characters in the query. I mean - the API server is expecting to get it. Is there any option to use it? – Art Bu Jan 28 '21 at 13:58
  • made it work with puting the encoded query in body fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' }, body: 'orderId=%D0%9C%D0%A3%D0%9797008058'}) – Art Bu Jan 28 '21 at 14:15
  • You might find that base62 encoding the URL parameters is useful to prevent unsafe URL characters. – dlaub3 Jan 28 '21 at 21:46

0 Answers0