2
votes

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.

3

3 Answers

1
votes

Regarding CORS, localhost behaves quite differently than remote origins, this can be very confusing.

I suspect that you didn't enable the CORS pre-flight OPTIONS endpoint. Your request is using a JOSN content type and therefore is not a "simple" cors request. It will be automatically preceded by an OPTION preflight request from the browser. Your server should be able to respond to that request.

See here how to enable it - https://www.npmjs.com/package/cors#enabling-cors-pre-flight

0
votes

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin.

You can do a CORS request from a HTTPS domain to another HTTPS domain. If you do http requests to call your https server, it is considered insecure an considered as force request to your server with tampered data.

Here,as I can see you are trying to access https server from your local http that's why you are getting an CORS issue.

0
votes

Do:

npm i --save cors

Add app.use(cors()) in server.js file.