In my Angular project, I take a screenshot that I get in base64 format in order to send it with a POST
request.
Everything works but, when I put it in production mode, I have a CORS error.
I think it's linked because a base64 is a long string
I tried header:
Content-type: application/octet-stream
,
Content-type: application/json
.
CORS error:
CORS config:
app.use(cors());
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*'),
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization',);
if (req.method === 'OPTIONS') {
res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');
return res.status(200).json({});
}
next();
});
Angular request :
headers = { 'Content-Type': 'application/json' };
generateSignature(signature) {
const data = {signature:signature}
return this.http
.post(this.url 'generateSignature',JSON.stringify(data) , { headers: this.headers} )
.toPromise()
.then(res => res as any);
}
CodePudding user response:
The Access-Control-Allow-Headers
header should be specified in the response to the preflight request, but in your code, you're setting it in the response to the actual request.
Also, you're both using Express's CORS middleware and setting CORS headers "manually". There's no need for that. Just configure the middleware properly:
const options = {
origin: 'http://localhost:4200',
optionsSuccessStatus: 200,
methods: ['PUT', 'POST', 'PATCH', 'DELETE', 'GET'],
allowHeaders: ['X-Requested-With', 'Content-Type', 'Accept', 'Authorization']
};
app.use(cors(options));
Finally, there's never a need to list Origin
in the allowed headers, because that request header is automatically set by the browser itself and therefore gets a pass.
CodePudding user response:
Sorry for the lack of information
app.use(cors());
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*'),
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization',);
if (req.method === 'OPTIONS') {
res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');
return res.status(200).json({});
}
next();
});
Angular request :
headers = { 'Content-Type': 'application/json' };
generateSignature(signature) {
const data = {signature:signature}
return this.http
.post(this.url 'generateSignature',JSON.stringify(data) , { headers: this.headers} )
.toPromise()
.then(res => res as any);
}