koajs / koa

Expressive middleware for node.js using ES2017 async functions
https://koajs.com
MIT License
35.07k stars 3.22k forks source link

[fix] I can not get query parameters about Korean #1787

Closed shaan-lee closed 9 months ago

shaan-lee commented 9 months ago

Describe the bug

Node.js version: v16.20.2

OS version: mac m2 mac OS 13.6.1

Description:

Actual behavior

when i request to my localhost in GET method, include url parameters example) http://localhost:4000/api/query?name=한글

in server output of ctx.query is { name: 'í\x95\x9Cê¸\x80' } how can i convert it to natural string?

Expected behavior

Code to reproduce

Checklist

shaan-lee commented 9 months ago

i am useing below dependency in server

import Koa from "koa"; import Router from "koa-router"; import bodyParser from "koa-bodyparser"; import json from "koa-json";

lagden commented 9 months ago

@shaan-lee

Inside the middleware method

function sample(ctx) {
  const {name} = ctx.query

  const uint8 = Uint8Array.from([...name].map(c => c.codePointAt(0)))
  const str = new TextDecoder().decode(uint8)

  console.log({uint8, str})
  // => { uint8: Uint8Array(6) [ 237, 149, 156, 234, 184, 128 ], str: '한글' }

  ctx.body = str
}

Hope this helps! 😉

shaan-lee commented 9 months ago

thank you, i solve the problem below code

app.use(async (ctx: Koa.Context, next: Koa.Next) => {
    const query = ctx.query;
    for (const q in query) {
        const queryValue = String(query[q]);
        const queryCodePoint = Uint8Array.from([...queryValue]
            .map(c => Number(c.codePointAt(0))));
        const queryStr = new TextDecoder().decode(queryCodePoint);
        query[q] = queryStr;
    }
    ctx.query = query;
    await next();
})

your code was very helpful!