【发布时间】:2020-05-29 20:46:09
【问题描述】:
我有一个快速 API 正在运行,当我提出请求时,我会收到此消息。
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 这是我的代码:
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);
});
请帮助我。我感谢所有的回应。提前谢谢。
【问题讨论】:
-
你的服务器在 4222 上运行?
-
节点服务器运行在端口:9000 和前端(角度)运行在端口:4222
-
不,我没有设置除此代码之外的任何其他内容。
-
嗯,不过,我在您的示例代码中看不到任何服务
api/courses的内容。那怎么不是404? -
@mike,现在我已经更新了所有代码。请再次检查