How to fix CORS issue http request in Angular 5 [duplicate]

被刻印的时光 ゝ 提交于 2019-12-04 22:04:48

CORS is a tool employed by browsers to prevent one origin (localhost in your case) from accessing resources from another (example.com) without the server explicitly saying you can access it via CORS headers like Access-Control-Allow-Origin and others.

It is the server that needs to provide those headers in order for you to access it's resources.

Mozilla has a good write up on it here.

// Add CORS header.

Example :

const Url = 'http://localhost:3000/';
const headers = new Headers;
const body = JSON.stringify(
{
title: "data" 
});
headers.append('Access-Control-Allow-Origin', '*');
this.http.post(Url, body, { headers: headers })
.pipe(map(res => res))
.catch(err => err);

// you can also use HTTP headers

import { HttpHeaders } from '@angular/common/http';

let header = new HttpHeaders();
header.set('Access-Control-Allow-Origin', '*');

Are you sure you have got http:// part in your apiUrl varialble send as an argument of postFormData function. That http:// part looks very essential while using HttpClient functions.

Leroy

CORS can only be managed server-side using the Access-Control-Allow-Origin header.

In your case, when serving Angular client side at localhost:4200, you have 2 options for the value of this header:

  1. Add * -- this will enable all origins (not recommended in production environment)
  2. Add localhost:4200 (including the port!) -- that will explicit grant only the domain+port to your server
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!