belyalov / tinyweb

Simple and lightweight HTTP async server for micropython
MIT License
239 stars 40 forks source link

UTF-8 char garbled in json response by frontend #21

Open hyzeer opened 4 years ago

hyzeer commented 4 years ago

Hi, thanks for your new firmware, it can handle UTF-8 char properly, but it has new problem about garbling. my codes is the following:

@websvr.resource('/config/wifi/aplist', method='GET')
async def connect_to_ap(data):
    gc.collect()
    sta = network.WLAN(network.STA_IF)
    sta.active(True)
    ap_list = sta.scan()
    resp = json.dumps({
        "msg": "OK",
        "result": [
            {"ssid": x[0].decode(), "authmode": x[4], "rssi": x[3]}
            for x in ap_list
        ]
    })
    for s in resp:
        yield s

the above codes works correctly if values of resp['result'] contains no UTF-8 chars, otherwise the front end would receive unreadable code, like this: 图片

I guess this due to Content-Type field should not be 'application/json;charset=utf-8' in Response-Header, but I can't debug it..

belyalov commented 4 years ago

Hi,

I think we can add override for encoding, let me try it (however it will take time, busy days)

hyzeer commented 4 years ago

Thanks for your reply in busy days. :)

another point, at v1.3.3, chars length handle error, I did this to avoiding the error:

 for x in ap_list:
      difference = len(x[0].decode().encode('utf-8')) - len(x[0].decode())
      yield '"ssid": "{}",'.format(x[0].decode()) + 'a' * difference

I used the above codes, utf-8 chars can be handled propely by tinyweb and decoded correctly by the browser. I don't know why it happened. 🤣