我使用了"cors"但我发现“对XMLHttpRequest的访问已被阻止".为什么? [英] I have used "cors" but I found "Access to XMLHttpRequest has been blocked". Why?

查看:57
本文介绍了我使用了"cors"但我发现“对XMLHttpRequest的访问已被阻止".为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行一个快速API,当我发出请求时,我会收到此消息.

I have an express API running and when I make a request I get this message.

Error:
Access to XMLHttpRequest at 'http://localhost:9000/api/courses' from origin
'http://localhost:4222' has been blocked by CORS policy: 
No 'Access-Control-Allow-Origin' header is present on the requested resource.

我在我的API中使用 cors ,这是我的代码:

I am using cors in my API here is my code:

import * as express from 'express';
import {Application} from "express";
import {getAllCourses, getCourseById} from "./get-courses.route";
import {searchLessons} from "./search-lessons.route";
import {loginUser} from "./auth.route";
import {saveCourse} from "./save-course.route";

const bodyParser = require('body-parser');
const app: Application = express();

app.use(bodyParser.json());
var cors = require('cors');
app.use(cors());

app.route('/api/login').post(loginUser);
app.route('/api/courses').get(getAllCourses);
app.route('/api/courses/:id').put(saveCourse);
app.route('/api/courses/:id').get(getCourseById);
app.route('/api/lessons').get(searchLessons);

const httpServer = app.listen(9000, () => {
    console.log("HTTP REST API Server running at http://localhost:" + httpServer.address().port);
});

请帮助我.我感谢所有回复.提前谢谢.

Kindly assist me. I appreciate all responses. Thanks Ahead.

推荐答案

给它一个原点

app.use(cors({
  origin: 'http://yourapp.com'
}));

这篇关于我使用了"cors"但我发现“对XMLHttpRequest的访问已被阻止".为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆