Fetch: post json data, application/json change to text/plain
The problem is that when you work in 'mode' 'no-cors', the Headers become an immutable and you will not be able to change some of its entries. One of the heads you can't change is the Content-Type. When you set 'mode' to 'no-cors' you will be able to change only these headers:
Accept
Accept-Language
Content-Language
Content-Type
and whose value, once parsed, has a MIME type (ignoring parameters) that isapplication/x-www-form-urlencoded
,multipart/form-data
, ortext/plain
In another words, in 'mode' '-no-'cors' you can only set application/x-www-form-urlencoded
, multipart/form-data
, or text/plain
to the Content-Type
.
So the solution is stop using fetch or changing it to 'cors' 'mode'. Of course this will only works if your server also accepts 'cors' requests.
Here is an example of how you could enable CORS in an Apache Server
SetEnvIfNoCase Access-Control-Request-Method "(GET|POST|PUT|DELETE|OPTIONS)" IsPreflight=1
SetEnvIfNoCase Origin ".*" AccessControlAllowOrigin=$0
SetEnvIfNoCase Origin "https://(url1.com|url2.com)$" AccessControlAllowOrigin=$0
Header always set Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS" env=IsPreflight
Header always set Access-Control-Allow-Headers "Content-Type, Authorization, Accept, Accept-Language" env=IsPreflight
Header always set Access-Control-Max-Age "7200" env=IsPreflight
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteCond %{ENV:IsPreflight} 1
RewriteRule ^(.*)$ $1 [R=204,L]
The above code will inject the CORS headers in the response when its necessary. With this code your server will allow CORS only from the the domains "url1.com" or "url2.com".
Here are some references
- https://developer.mozilla.org/en-US/docs/Web/API/Request/mode
- https://fetch.spec.whatwg.org/#simple-header
Thanks a lot! More than 6 hours to solve this.
In my nodejs server
npm install --save cors
at app.js I inserted the lines:
var cors = require('cors');
var app = express();
app.use(cors());
and in my react client:
var shape_for_db = JSON.stringify(layer.geometry);
const trechoRede = {
method: "POST",
mode: "cors",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: shape_for_db
};
The mode:"no-cors"
options appears to be the issue. Remove that option and the Content-Type
should be set to "application/json"