【问题标题】:I have used "cors" but I found "Access to XMLHttpRequest has been blocked". Why?我使用了“cors”,但发现“对 XMLHttpRequest 的访问已被阻止”。为什么?
【发布时间】: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,现在我已经更新了所有代码。请再次检查

标签: node.js express cors


【解决方案1】:

给它一个起源

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

【讨论】:

    猜你喜欢
    • 2022-01-01
    • 2019-12-18
    • 2022-08-14
    • 2019-12-16
    • 2020-03-12
    • 2020-05-05
    • 2019-04-28
    • 2020-05-30
    相关资源
    最近更新 更多