-1

I have looked at and troubleshot with many different posts on stack overflow of people having similar or the same issue, however, no solutions seem to work for me.

I keep getting the error Access to XMLHttpRequest at 'http://localhost:3000/email?email=j' from origin 'https://mai...' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I thought adding app.use(cors()); would fix it, but the problem persists.

const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const mongoose = require("mongoose");

var userController = require("./controllers/userController.js");
var emailController = require("./controllers/emailController.js");

var app = express();

app.use(cors());

mongoose.connect(
  "redactedForStackOverflow",
  { useUnifiedTopology: true, useNewUrlParser: true },
  err => {
    if (!err) console.log("MongoDB connection succeeded...");
    else
      console.log(
        "Error in DB connection : " + JSON.stringify(err, undefined, 2)
      );
  }
);

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use("/", express.static(path.join(__dirname, "angular")));

var port = 3000;

app.listen(process.env.PORT || port, () =>
  console.log("Server started at port : " + port)
);

app.use("/users", userController);
app.use("/email", emailController);
app.use((req, res, next) => {
  res.sendFile(path.join(__dirname, "angular", "index.html"));
});

module.exports = app;

EDIT

Adding service file

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/operator/toPromise';

import { User } from './user.model';
import { UserComponent } from '../user/user.component';

@Injectable({
  providedIn: 'root'
})
export class UserService {
  selectedUser: User;
  users: User[];
  readonly baseURL = 'http://localhost:3000/users';
  codeSentIn;

  constructor(private http: HttpClient) {}

  postUser(users: User) {
    const codeOnItsWay = this.codeSentIn;
    this.resetCode();
    return this.http.post<any>(this.baseURL, {users, codeOnItsWay});
  }

  resetCode() {
    this.codeSentIn = '';
  }

  getUserList() {
    return this.http.get(this.baseURL);
  }

  getSpecificUser(id) {
    return this.http.get<any>(this.baseURL + '/' + id);
  }

  findPositionInLine(email) {
    return this.http.get<any>(this.baseURL + '/positionInLine/' + email);
  }

  getUserForLogin(email) {
    return this.http.get(this.baseURL + '/login/' + email);
  }

  sendEmailToCheck(emailToCheck) {
    return this.http.get('http://localhost:3000/email', { params: { email: emailToCheck }});
  }
}

Ryan Soderberg
  • 585
  • 4
  • 21
  • Does this answer your question? [Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?](https://stackoverflow.com/questions/7067966/why-doesnt-adding-cors-headers-to-an-options-route-allow-browsers-to-access-my) – Ray Jan 17 '20 at 01:03
  • @Raymond If you scroll down to the post below the one marked as the answer, it displays what I'm trying to do – Ryan Soderberg Jan 17 '20 at 01:08
  • 1
    Can you show the client-side code making the request so we can see exactly what the request is. Also, `app.use(cors());` is not sufficient for all possible cross origin requests. We need to know what's in the actual request because you probably have to do more than that and support an OPTIONS request handler. If you look in the network tab of the chrome debugger and the actual request that's being sent you will learn a bunch. If you share that with us, then we can help you better. – jfriend00 Jan 17 '20 at 01:08
  • @RyanSoderberg but I can't see you set the header 'Access-Control-Allow-Origin', if you look in the second part of it, you need to add `res.set('Access-Control-Allow-Origin', '*');` to set header in your request – Ray Jan 17 '20 at 01:11
  • Hi @jfriend00, I've added my services from the client side to the OP – Ryan Soderberg Jan 17 '20 at 01:13
  • Have you tried clearing cache? – Lev Kuznetsov Jan 17 '20 at 01:14
  • Which request in that client code? – jfriend00 Jan 17 '20 at 01:15
  • @jfriend00 `sendEmailToCheck()` , though it is the only one I've tried so far } – Ryan Soderberg Jan 17 '20 at 01:19
  • have you tried the white list option from cors ? – Ray Jan 17 '20 at 01:25
  • What’s the HTTP status code of the response? You can use the Network pane in browser devtools to check. Is it a 4xx or 5xx error rather than a 200 OK success response? – sideshowbarker Jan 17 '20 at 01:29
  • OK, if I were debugging this, I would next look at the network tab in the Chrome debugger and see exactly what the client is sending to the server for that request (including headers) and then see exactly what the server is responding with. And, I'd look to see if the browser is sending an OPTIONS pre-flight request instead of the GET request. And, we could help you better if you shared all that with us. – jfriend00 Jan 17 '20 at 01:30
  • @Raymond Your deleted response worked! – Ryan Soderberg Jan 17 '20 at 01:32
  • @RyanSoderberg ah nice, i have recovered it – Ray Jan 17 '20 at 01:34

1 Answers1

-1

Update: possible missing cors option:

 var corsOptions = {
 origin: 'localhost:3000',
 credentials : true
}

as mentioned from here : Node JS CORS module not setting Access-Control-Allow-Credentials header

Alternatively, Remove app.use(cors());

You can manually add header in all your requests :

app.use((req, res,next) => {
  res.set('Access-Control-Allow-Origin', '*');
  next();
});

Just add the above code block before

app.use("/users", userController);
app.use("/email", emailController);
app.use((req, res, next) => {
  res.sendFile(path.join(__dirname, "angular", "index.html"));
});
Ray
  • 1,539
  • 1
  • 14
  • 27
  • 4
    That's what `app.use(cors())` already does. It already adds the `'Access-Control-Allow-Origin'` header. That's part of the point of using it. – jfriend00 Jan 17 '20 at 01:17