Я смотрел и устранял проблемы со многими различными сообщениями о переполнении стека людей, имеющих похожую или одинаковую проблему, однако, похоже, что решения для меня не работают.
Я получаю сообщение об ошибке 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.
Я думал, что добавление app.use(cors());
исправит это, но проблема остается.
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;
РЕДАКТИРОВАТЬ
Добавление служебного файла
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 }});
}
}