Issue
The method and contentType parameters doesn’t exchange in HttpRequest (web client) and HttpRequest (server) in Dart.
I have the following code:
(Web Client)
var url = "http://127.0.0.1:8087";
String jsonString = JSON.encode(dadosRegistro[id]);
HttpRequest.request(url, method: "DELETE", sendData: jsonString, mimeType: "application/json")
.then((HttpRequest resp) {
window.console.log(resp.response);
}).catchError(tratarErro);
(Server)
HttpServer.bind('127.0.0.1', 8087).then((server) {
server.listen((HttpRequest request) {
print(request.method);
print(request.headers.contentType);
});
When the Web Client calls server, the result is the following:
OPTIONS
null
My expectative was:
DELETE
application/json
Am I doing anything wrong?
Thanks!
Solution
This is a CORS issue. The request you are receiving is actually the pre-flight request, sent by the browser to verify if the server can receive the actual request. You can see more about CORS here: http://www.html5rocks.com/en/tutorials/cors/
To see the expected result, you can change your server code to handle the pre-flight request:
HttpServer.bind('127.0.0.1', 8087).then((server) {
server.listen((HttpRequest request) {
request.response.headers.add("Access-Control-Allow-Origin", "*");
request.response.headers.add("Access-Control-Allow-Methods", "POST,GET,DELETE,PUT,OPTIONS");
request.response.statusCode = HttpStatus.OK;
if (request.method == "OPTIONS") {
//pre-flight request
request.response.close();
} else {
print(request.method);
print(request.headers.contentType);
request.response.close();
}
});
Answered By – luizmineo
Answer Checked By – Candace Johnson (FlutterFixes Volunteer)