I'我想把Cors添加到我建立的这个特定的角度服务中.我该如何实现这一点



我的angular服务基本上是从api中获取电影及其细节。我相信,如果不是这个问题,它会起作用。我意识到有很多方法可以绕过紧身胸衣,但我真的想要基于我现有的最简单的方法。我怎样才能做到这一点?

服务页面.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}`);
}
}

这是我从样板中得到的后端。它目前只显示Api正在9000端口上运行。我不知道如何将它连接到我的前端,这样紧身胸衣就不是问题了。

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);
});
}

恐怕您无法"绕过"CORS。至少不要更改前端/Angular应用程序的任何内容。如果您的请求因为CORS而被拒绝(我认为这就是问题所在(。您必须允许您的域位于后端,而不是前端。

最新更新