Friday, April 8, 2022

[SOLVED] using curl and json with express server

Issue

I wanted to test some api on my local express server using curl and json formated datas, following curl documentation, like :

curl -v -k https://www.localhost.fr/api/test -H 'Content-Type:application/json' -d '{"test":"test"}'

No json parsed in express and exposed headers are wrong :

''Content-Type'
'application/json''

I removed quotes from Content-type, headers are correct but now express.json() middleware send an error :

Unexpected token ' in JSON at position 0

I tried to rewrite datas :

{"test":"test"}

{test:test}

"test"

"{\'test':\'test\'}"

..etc I think I tried all ways i could to write them..

only {} an "{}" don't throw parse error

I tried then to look at what express receive as datas using middleware raw(), on top of json's one, and I get nothing to parse, no body, no datas. (second issue/misunderstanding here)

I specify everything works fine outside curl (react app using fetch).

curl 7.79.1, nodejs 16, express 4

Somebody ran into this issue? curl is a cool tool, but i'm really confused here.. ;(, Thanks in advance!


Solution

On Windows, you must use double quotes: curl -H "Content-Type:application/json" -d "{\"test\": \"test\"}" ...



Answered By - Heiko Theißen
Answer Checked By - Robin (WPSolving Admin)