Search code examples
angularservicecorsget-requesthttp-options-method

I'd like to add Cors to this specific angular service that I have built How can I achieve this?


My angular service basically goes and retrieves a movie and it's details from an api. I believe it will work if not for this cors issue. I realize that there are many ways to get around cors but I really want the simplest way based upon what I already have. How can I achieve this?

service page.ts

import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import { map } from 'rxjs/operators';

 //Typescript custom enum for search tpes (optional)
 export enum SearchType{
 all = '',
 movie = 'movie',
 series = 'series',
 episode = 'episode'
 }


 @Injectable ({
 providedIn : 'root'
 })
 export class MovieService {
 url = 'http://www.omdapi.com/';
 apiKey = '*******' //my api key here!


 constructor (private http: HttpClient) {}

 searchData(title: string, type: SearchType): 
 Observable<any> {
 return this.http.get(`${this.url}? 
 s=${encodeURI(title)}&type=${type}&apikey=${this.apiKey}`).pipe(
  map(results => results['Search'])
  );
 }

  getDetais(id){
  return this.http.get(`${this.url}? 
  i=${id}&plot=full&apikey=${this.apiKey}`);
  }

 }

Here's the backend I got from a boilerplate. It currently just displays Api is running on port 9000. I'm not sure how to connect this to my front end so that cors isn't an issue.

main.js

import * as express from 'express';
import {Application} from "express";
import * as cors from "cors";

export function initServer() {

const bodyParser = require('body-parser');

const app:Application = express();

app.use(cors());

app.route("/").get((req, res) => {
    res.status(200).send("<h1>API is up and running!</h1>");
});


const PORT = process.env.PORT || 9000;

app.listen(PORT, () => {
    console.log("HTTP REST API Server running at port " + PORT);
});

}

Solution

  • I'm afraid you can't "get around" CORS. At least not by changing anything on the side of your frontend/Angular app. If your requests are getting rejected because of CORS (which I assume is the issue). You'll have to allow your domain on your backend and not your frontend.