Cors为什么阻止我对Api的请求?

编程入门 行业动态 更新时间:2024-10-07 08:29:57

Cors为什么阻止<a href=https://www.elefans.com/category/jswz/34/1770129.html style=我对Api的请求?"/>

Cors为什么阻止我对Api的请求?

我正在开发一个项目,并且需要访问我开发的Api


const endpoint = 'localhost:3000/api/v1/';
const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
  }),
};

@Injectable({
  providedIn: 'root',
})
export class RestService {
  constructor(private http: HttpClient) {}

  private extractData(res: Response) {
    let body = res;
    return body || {};
  }

  getRequest(id: String): Observable<Request> {
    return this.http.get<Request>(endpoint + 'request/' + id, httpOptions);
  }

我已经授予了权限,以便可以访问它,但出现此错误

ccess to XMLHttpRequest at 'localhost:3000/api/v1/request/5ec3fbd84fe7bf4aa8d48b39' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

这里是权限:

app.use(
  cors({
    credentials: true,
    origin: "http://localhost:4200",
  })
);
回答如下:

这不是您的客户端中的问题,它始终是后端中丢失(或错误)的配置。

我认为您使用的是nodejs和express。

尝试以此设置cors标头:

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors());  // it must be in the beginning!

如果可以,则可以减少可能的URL。

参见:https://expressjs/en/resources/middleware/cors.html

更多推荐

Cors为什么阻止我对Api的请求?

本文发布于:2024-05-07 20:40:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1757154.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:我对   Cors   Api

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!