full error message : POST http://localhost:4200/api/user/login 504 (Gateway Timeout)
when trying to create a login function in my angular app and have it communicate with the express backend i get the 504 error shown above. I've included snippets of what i think is all the relevant code below.
running on localhost:4200 trying to reach localhost:3000 that the server is being run on.
app.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const url = 'mongodb srv://josh:*******@cluster0.cwv6f.mongodb.net/Unionise?retryWrites=true&w=majority';
const User = require('./models/user.model');
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended : false}))
app.post('/api/user/login', (req, res) => {
mongoose.connect(url,{ useMongoClient: true }, function(err){
if(err) throw err;
User.find({
username : req.body.username, password : req.body.password
}, function(err, user){
if(err) throw err;
if(user.length === 1){
return res.status(200).json({
status: 'success',
data: user
})
} else {
return res.status(200).json({
status: 'fail',
message: 'Login Failed'
})
}
})
});
})
app.get('/api/user/login', (req, res) => {
res.send('Hello World!')
})
app.listen(3000, () => console.log('blog server running on port 3000!'))
login.component.ts
import { AppService } from './../app.service';
import { Component, OnInit } from '@angular/core';
import { LoginService } from './login.service';
import { User } from '../models/user.model';
import { response } from 'express';
import { Console } from 'console';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
providers: [ LoginService ]
})
export class LoginComponent implements OnInit {
public user : User;
success = "";
constructor(private loginService: LoginService, public appService: AppService) {
this.user = new User();
}
validateLogin() {
if(this.user.username && this.user.password) {
this.loginService.validateLogin(this.user).subscribe(result => {
console.log('result is ', result);
}, error => {
console.log('error is ', error);
});
} else {
alert('enter user name and password');
}
}
ngOnInit(): void {
// this.appService.login().subscribe(
// response=>{
// this.success = response.status;
// console.log(this.success);
// },
// error => {}
// );
}
}
login.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { User } from '../models/user.model';
@Injectable()
export class LoginService {
constructor(private http: HttpClient){
}
validateLogin(user: User){
return this.http.post('/api/user/login',{
username : user.username,
password : user.password
})
}
}
routing
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LoginComponent } from './login/login.component';
const routes: Routes = [
{ path: '', component: LoginComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
proxy
{
"/api/*": {
"target": "http://localhost:3000",
"secure": "false"
}
}
Command console errors: Angular app
<e> [webpack-dev-server] [HPM] Error occurred while proxying request localhost:4200/api/user/login to http://localhost:3000/ [ECONNRESET] (https://nodejs.org/api/errors.html#errors_common_system_errors)
server
C:\Users\joshk\Documents\GitHub\Unionise\server\node_modules\mongoose\lib\helpers\promiseOrCallback.js:20
throw error;
^
MongoParseError: option usemongoclient is not supported
at parseOptions (C:\Users\joshk\Documents\GitHub\Unionise\server\node_modules\mongodb\lib\connection_string.js:289:15)
at new MongoClient (C:\Users\joshk\Documents\GitHub\Unionise\server\node_modules\mongodb\lib\mongo_client.js:62:63)
at C:\Users\joshk\Documents\GitHub\Unionise\server\node_modules\mongoose\lib\connection.js:784:16
at new Promise (<anonymous>)
at NativeConnection.Connection.openUri (C:\Users\joshk\Documents\GitHub\Unionise\server\node_modules\mongoose\lib\connection.js:781:19)
at C:\Users\joshk\Documents\GitHub\Unionise\server\node_modules\mongoose\lib\index.js:340:10
at promiseOrCallback (C:\Users\joshk\Documents\GitHub\Unionise\server\node_modules\mongoose\lib\helpers\promiseOrCallback.js:10:12)
at Mongoose._promiseOrCallback (C:\Users\joshk\Documents\GitHub\Unionise\server\node_modules\mongoose\lib\index.js:1140:10)
at Mongoose.connect (C:\Users\joshk\Documents\GitHub\Unionise\server\node_modules\mongoose\lib\index.js:339:20)
at C:\Users\joshk\Documents\GitHub\Unionise\server\app.js:20:11
Node.js v17.4.0
CodePudding user response:
Your problem is that You're creating connection when request comes in.
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const url = 'mongodb srv://josh:*******@cluster0.cwv6f.mongodb.net/Unionise?retryWrites=true&w=majority';
const User = require('./models/user.model');
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended : false}))
app.post('/api/user/login', async (req, res) => {
try {
const query = {
username: req.body.username,
password: req.body.password,
};
const user = await User.findOne(query).lean();
if (!user) {
return res.status(200).json({
status: 'fail',
message: 'Login Failed'
});
}
res.status(200).json({
status: 'success',
data: user
});
}
catch (error) {
console.error(error.message);
res.status(500).end();
}
})
app.get('/api/user/login', (req, res) => {
res.send('Hello World!')
})
const PORT = process.env.PORT || 3000;
// CONNECTION MUST BE ONCE AT START!
mongoose.connect(
url, {},
(err) => {
if (err) {
console.error('DB: fail');
console.error(err.message);
process.exit(1);
}
console.log('DB: connected');
app.listen(PORT, () => console.log('blog server running on port', PORT));
});