我对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的请求?
发布评论