I have used “cors” but I found “Access to XMLHttpRequest has been blocked”. Why?

ε祈祈猫儿з 提交于 2021-02-20 03:41:42

问题


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.

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.


回答1:


Give an origin to it

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


来源:https://stackoverflow.com/questions/60219757/i-have-used-cors-but-i-found-access-to-xmlhttprequest-has-been-blocked-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!