问题
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