[Error] Bad state: Cannot set the body fields of a Request with content-type "application/json"
문제점
content type을 application/json으로 넣을 경우의 body엔 application/json에 맞게 String값이 들어가야하는데 map형식으로 넣어서 문제 발생
다시 말해서 application/json은 json string(json 형태를 문자열로 입력하는 형식)타입을 전송한단 것을 의미하기 때문에 map으로 넣으면 안되는 것
해결방법
map형식인 데이터를 dart:convert 패키지 내의 jsonEncode함수로 래핑하여 String으로 변경되어 들어가도록 구현
예시는 아래와 같다.
import 'package:http/http.dart';
import 'dart:convert';
func() async {
final result = await post(Uri.parse('http://10.0.2.2:3000/api/account/login'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode(data.toJson())
);
}
content type이 application/x-www-form-urlencoded이여도 상관없다면 content type을 직접 헤더로 선언하지 않고 body에 map을 넣으면 content type이 기본적으로 application/x-www-form-urlencoded으로 들어가므로 key:value형식으로 전송되므로 문제없이 전송가능하다.
IANA에 따라 json형식은 application/json형식으로 전송하는 것이 맞음
이 문제는 content type에 대한 이해가 부족해서 발생한 것이므로 제대로 된 공부가 필요
Bad state: Cannot set the body fields of a Request with content-type "application/json"
Map<String,String> headers = {'Content-Type':'application/json','authorization':'Basic c3R1ZHlkb3RlOnN0dWR5ZG90ZTEyMw=='}; var response = await post(Urls.getToken, headers: headers, ...
stackoverflow.com
Bad state: Cannot set the body fields of a Request with content-type "application/json" · Issue #167 · dart-lang/http
I can't make simple POST request with header 'content-type' : 'application/json'. With some investigation, i figure out this source code else if (contentType.mimeType != "a...
github.com
What is the Correct Content-Type for JSON? Request Header Mime Type Explained
Every resource used on the internet has a media type, also known as a MIME type which stands for Multipurpose Internet Mail Extension. This information is necessary for transactions between server and client. The browser needs to know the media type of res
www.freecodecamp.org