Good Morning. I have a problem with Cors on my backend, Cors indicates that the ip address I whitelist is not the same as the one my frontend uses.
This is the service that sends the data to the backend:
import { Injectable } from '@angular/core'; import { Persona } from '../modelos/persona'; import { Observable, throwError } from 'rxjs'; import { catchError, tap, map } from 'rxjs/operators'; import {HttpClient,HttpErrorResponse,HttpHeaders }from '@angular/common/http' @Injectable({ providedIn: 'root', }) export class PersonaService { headers=new HttpHeaders(); selectedPersona: Persona; personas:Persona[]; readonly URL_API='http://localhost:3000/Inicio/Persona'; constructor(private http: HttpClient) { this.selectedPersona=new Persona(); } postPersona(persona:Persona){ return this.http.post(this.URL_API,persona) }
The request comes from http://209.145.52.133:8080 which is my front
In my Backend I set the allowed address:
app.use(cors({origin:'http://209.145.52.133:8080'}));
And in the end it returns the error:
Access to XMLHttpRequest at 'http://localhost:3000/Inicio/Login' from origin 'http://209.145.52.133:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'http://209.145.52.133/' that is not equal to the supplied origin.
This may help you
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization',
);
res.header(
'Access-Control-Allow-Methods',
'GET,POST,fetch, PATCH,OPTIONS,DELETE',
);
res.header('Access-Control-Allow-Credentials', true);
if (req.method === 'OPTIONS') {
res.header(
'Access-Control-Allow-Methods',
'PUT, POST, PATCH,FETCH, DELETE, GET',
);
return res.json({});
} else {
next();
}
});
If not you can try this one from express cors documentation
var corsOptions = {
origin: 'http://example.com',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
app.get('/products/:id', cors(corsOptions), function (req, res, next) {
res.json({msg: 'This is CORS-enabled for only example.com.'})
})
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.