简体   繁体   中英

Postman form-data and x-www-form-urlencoded work but raw json doesn't

I have a form that sends credentials to an endpoint for authentication and it should return a token. I want to replace the HTML form with javascript but I can't get it to work. To find out why it doesn't work I've tried to do the same with Postman and I get the result that when I send the POST request with body as form-data it works fine. Sending it as x-www-form-urlencoded also works fine, but when I send it as json (Content-Type: "application/json") it doesn't.

The request JSON data:

{
    "username": "my_username",
    "password": "my_password",
    "referer": "http://127.0.0.1:5500",
    "f": "json"
}

my_password contains letters, dots and underscores but no other special characters. my password only has an exclamation mark as a special character.

Can the endpoint distinguish between a form being sent or javascript (fetch API)? Also, is there any reason why an endpoint could not work when sending json instead of the other two options?

Can the endpoint distinguish between a form being sent or javascript (fetch API)?

Not really.

If it a cross-origin request then JS will add an Origin header.

Client-side code could also explicitly add a different header.

is there any reason why an endpoint could not work when sending json instead of the other two options?

If the endpoint isn't designed to parse JSON formatted requests.


It sounds like you are over-complicating things.

Just write your JS code to make the POST request using application/x-www-form-urlencoded or multipart/form-data (since those are the formats it supports) instead of JSON.

You could alternatively rewrite the endpoint to support JSON.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM