Server.js Code:
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors')
const db = require('./DB/db');
const routes = require('./api/routes/routes');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cors({
origin: '*'
}));
routes(app);
app.listen(PORT, () => {
console.log(`Server started at ${PORT}`);
});
package.json file:
{
"name": "LMS_Backend",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"joi": "^14.3.1",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.9.11",
"nodemailer": "^6.4.6"
}
}
Angular service file:
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
const baseUrl = 'https://lmspreject-1.herokuapp.com/api/lms_project';
// const baseUrl = 'http://localhost:3000/api/lms_project';
@Injectable({
providedIn: 'root',
})
export class AdminServiceService {
constructor(private http: HttpClient) {}
register(adminDetails) {
console.log(adminDetails);
let headers = new HttpHeaders({
'Content-Type': 'application/json',
'Accept': 'application/json'
});
let options = {
headers: headers,
};
return this.http.post(`${baseUrl}/admin/register`, adminDetails, options);
}
}
Error:
Access to XMLHttpRequest at 'https://lmspreject-1.herokuapp.com/api/lms_project/admin/register' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Note: It works fine I run the app on the localhost but gives error on Heroku URL.