Internal server error 500 when making POST request to server - javascript

I am trying to make a social media app project using React and MongoDB but whenever I am trying to register a user I get a POST error from the console. I tried checking my client-side and server-side code but I still can't get the user info to post and register.
**EDIT **
Thank you for the tips on how to make a better question here is my second attempt at a more clear post
The main error I'm getting in the console is this:
> POST http://localhost:3001/auth/register 500 (Internal Server Error)
> register # Form.jsx:56 handleFormSubmit # Form.jsx:89
> (anonymous) # Formik.tsx:849 (anonymous) # Formik.tsx:1200
> (anonymous) # Formik.tsx:756 Promise.then (async)
> (anonymous) # Formik.tsx:731 (anonymous) # Formik.tsx:1200
> (anonymous) # Formik.tsx:823 (anonymous) # Formik.tsx:1200
> callCallback # react-dom.development.js:4164
> invokeGuardedCallbackDev # react-dom.development.js:4213
> invokeGuardedCallback # react-dom.development.js:4277
> invokeGuardedCallbackAndCatchFirstError # react-dom.development.js:4291
> executeDispatch # react-dom.development.js:9041
> processDispatchQueueItemsInOrder # react-dom.development.js:9073
> processDispatchQueue # react-dom.development.js:9086
> dispatchEventsForPlugins # react-dom.development.js:9097
> (anonymous) # react-dom.development.js:9288
> batchedUpdates$1 # react-dom.development.js:26140
> batchedUpdates # react-dom.development.js:3991
> dispatchEventForPluginEventSystem # react-dom.development.js:9287
> dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay # react-dom.development.js:6465
> dispatchEvent # react-dom.development.js:6457 dispatchDiscreteEvent
Upon further examination of the error through the browser console it is pointing me to this line of code in my Form.jsx file:
const savedUserResponse = await fetch("http://localhost:3001/auth/register", {
method: "POST",
body: formData,
});
This is the full block of code for my register function:
const register = async (values, onSubmitProps) => {
//send form info with an image
const formData = new FormData();
for (let value in values) {
formData.append(value, values[value]);
}
formData.append("picturePath", values.picture.name);
const savedUserResponse = await fetch("http://localhost:3001/auth/register", {
method: "POST",
body: formData,
});
const savedUser = await savedUserResponse.json();
onSubmitProps.resetForm();
if (savedUser) {
setPageType("login");
}
};
In my server side code this is the index.js that handles the auth:
// ROUTES WITH FILES
app.post("/auth/register", upload.single("picture"), register);
app.post("/posts", verifyToken, upload.single("picture"), createPost);
//ROUTES
app.use("/auth", authRoutes);
app.use("/users", userRoutes);
app.use("/posts", postRoutes);
// MONGOOSE
const PORT = process.env.PORT || 6001;
mongoose.set("strictQuery", false);
mongoose
.connect(process.env.MONGO_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
app.listen(PORT, () => console.log(`Server Port: ${PORT}`));
// User.insertMany(users);
// Post.insertMany(posts);
})
.catch((error) => console.log(`${error} did not connect`));
Register function from my auth.js in my controllers folder:
export const register = async (req, res) => {
try {
const { firstName, lastName, email, password, picturePath, friends, location, occupation } = req.body;
const salt = await bcrypt.genSalt();
const passwordHash = await bcrypt.hash(password, salt);
const newUser = new User({
firstName,
lastName,
email,
password: passwordHash,
picturePath,
friends,
location,
occupation,
viewedProfile: Math.floor(Math.random() * 10000),
impressions: Math.floor(Math.random() * 10000),
});
const savedUser = await newUser.save();
res.status(201).json(savedUser);
} catch (err) {
res.status(500).json({ error: err.message });
}
};
The response I get from the server :
"POST /auth/register HTTP/1.1" 500 248
Error: ENOENT: no such file or directory, open 'G:\WebDev\DesTracker\destracker-app\server\public,assets\p2.jpeg'
I'm expecting the user info to post to my database after I click register but instead I'm getting the interal server error 500

You will need to provide more information to get the best answer as #Yarin_007
said. However, I'll try to provide assistance with the minimal info provided.
A status 500 simply means you have an exception or an error on your server. Now, the warning has provided Where the error is, why you're getting that error and what the error is.
Where: You can find the error in the submitForm().
What: It is a SyntaxError which simply means you have deviated from the syntax of a sequence of characters or tokens of a programming language.
Why: We say so because '<', "<!DOCTYPE "... is not valid JSON.
This is the explanation of the error based on the information you provided. Get us more details about the error so we can help.
Happy coding!!!

Related

AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}

I am trying to implement authentication in my MERN stack. After I fill the register form, it should direct me to login page, instead, am getting this error below. I will appreciate if anyone can help me. thanks
xhr.js:220 POST http://localhost:5000/user/signup 500 (Internal Server Error)
dispatchXhrRequest # xhr.js:220
xhrAdapter # xhr.js:16
dispatchRequest # dispatchRequest.js:58
request # Axios.js:109
httpMethod # Axios.js:144
wrap # bind.js:9
signUp # index.js:11
(anonymous) # auth.js:18
(anonymous) # index.js:16
handleSubmit # register.js:25
callCallback # react-dom.development.js:4164
invokeGuardedCallbackDev # react-dom.development.js:4213
invokeGuardedCallback # react-dom.development.js:4277
invokeGuardedCallbackAndCatchFirstError # react-dom.development.js:4291
executeDispatch # react-dom.development.js:9041
processDispatchQueueItemsInOrder # react-dom.development.js:9073
processDispatchQueue # react-dom.development.js:9086
dispatchEventsForPlugins # react-dom.development.js:9097
(anonymous) # react-dom.development.js:9288
batchedUpdates$1 # react-dom.development.js:26140
batchedUpdates # react-dom.development.js:3991
dispatchEventForPluginEventSystem # react-dom.development.js:9287
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay # react-dom.development.js:6465
dispatchEvent # react-dom.development.js:6457
dispatchDiscreteEvent # react-dom.development.js:6430
auth.js:22 AxiosError {message: 'Request failed with status code 500', name: 'AxiosError', code: 'ERR_BAD_RESPONSE', config: {…}, request: XMLHttpRequest, …}code: "ERR_BAD_RESPONSE"config: {transitional: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, adapter: ƒ, …}message: "Request failed with status code 500"name: "AxiosError"request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}response: {data: {…}, status: 500, statusText: 'Internal Server Error', headers: {…}, config: {…}, …}[[Prototype]]: Error
This is my router
import express from "express";
import { signin, signup } from "../controllers/user.js";
const router = express.Router();
router.post('/signin', signin);
router.post('/signup', signup);
export default router;
This is my index.js for my server
app.use('/user', userRoutes);
this is my frontend route
import axios from "axios";
const API = axios.create({ baseURL: 'http://localhost:5000'})
export const fetchPosts = () =>API.get('/posts');
export const createPost = (newPost) =>API.post('/posts', newPost);
export const updatePost = (id, updatedPost) =>API.patch(`/posts/${id}`, updatedPost);
export const deletePost = (id) =>API.delete(`/posts/${id}`);
export const signIn = (values) => API.post('/user/signin', values)
export const signUp = (values) => API.post('/user/signup', values)

getMessaging failing - Uncaught SyntaxError: Cannot use import statement outside a module (at firebase-messaging-sw.js:1:1)

I'm trying to integrate firebase messaging into my NextJS web app but getting errors that potentially look like they're coming from the serverside. To get registrations working in _app.tsx I do the following:
useEffect(() => {
if ("serviceWorker" in navigator) {
window.addEventListener("load", function () {
const config = process.env.NEXT_PUBLIC_FIREBASE;
navigator.serviceWorker.register("/firebase-messaging-sw.js?firebaseConfig=" + Buffer.from(config).toString('base64'), {
type: 'module'
}).then(
function (registration) {
console.log("Service Worker registration successful with scope: ", registration.scope);
},
function (err) {
console.log("Service Worker registration failed: ", err);
}
);
});
}
}, [])
Where NEXT_PUBLIC_FIREBASE is the firebase config object.
Then in public/firebase-messaging-sw.js I have this:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.8.1/firebase-app.js";
import { getMessaging } from "https://www.gstatic.com/firebasejs/9.8.1/firebase-messaging.js";
const swScriptUrl = new URL(self.location);
const base64Config = swScriptUrl.searchParams.get('firebaseConfig')
let decoded = atob(base64Config);
const firebaseConfig = JSON.parse(decoded);
const app = initializeApp(firebaseConfig);
// Retrieve an instance of Firebase Messaging so that it can handle background
const messaging = getMessaging(app);
When getMessaging is called I get this error:
Uncaught SyntaxError: Cannot use import statement outside a module (at firebase-messaging-sw.js:1:1)
index.esm2017.js?f614:823 Uncaught (in promise) FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('http://localhost:3000/firebase-cloud-messaging-push-scope') with script ('http://localhost:3000/firebase-messaging-sw.js'): ServiceWorker script evaluation failed (messaging/failed-service-worker-registration).
at registerDefaultSw (index.esm2017.js?f614:823:1)
at async updateSwReg (index.esm2017.js?f614:847:1)
at async getToken$1 (index.esm2017.js?f614:910:1)
at async FirebaseMessagingWeb.getToken (web.js?00d2:24:1)
registerDefaultSw # index.esm2017.js?f614:823
Promise.then (async)
asyncGeneratorStep # ios-notification.ts?89f7:2
_next # ios-notification.ts?89f7:2
eval # ios-notification.ts?89f7:2
eval # ios-notification.ts?89f7:2
addListeners # ios-notification.ts?89f7:4
eval # notification-context.tsx?dccb:38
Promise.then (async)
registerForNotifications # notification-context.tsx?dccb:37
registerForNotifications # notification-context.tsx?dccb:62
onClick # profile-box.tsx?a1b7:280
callCallback # react-dom.development.js?ac89:4161
invokeGuardedCallbackDev # react-dom.development.js?ac89:4210
invokeGuardedCallback # react-dom.development.js?ac89:4274
invokeGuardedCallbackAndCatchFirstError # react-dom.development.js?ac89:4288
executeDispatch # react-dom.development.js?ac89:9038
processDispatchQueueItemsInOrder # react-dom.development.js?ac89:9070
processDispatchQueue # react-dom.development.js?ac89:9083
dispatchEventsForPlugins # react-dom.development.js?ac89:9094
eval # react-dom.development.js?ac89:9285
batchedUpdates$1 # react-dom.development.js?ac89:26096
batchedUpdates # react-dom.development.js?ac89:3988
dispatchEventForPluginEventSystem # react-dom.development.js?ac89:9284
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay # react-dom.development.js?ac89:6462
dispatchEvent # react-dom.development.js?ac89:6454
dispatchDiscreteEvent # react-dom.development.js?ac89:6427
firebase-messaging-sw.js:1 Uncaught SyntaxError: Cannot use import statement outside a module (at firebase-messaging-sw.js:1:1)
I've checked the config object and it definitely is correct and making it to the service worker (also tried just copying the config in to no avail).
Have tried getting this to work both locally and on a https server to no avail, I've also tried a none module import which produced the same error.
The same thing happened to me, the first is to use importScripts , and the second is to downgrade to 8.0.0 and change the function calls a bit. As I show you below:
importScripts("https://www.gstatic.com/firebasejs/8.0.0/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/8.0.0/firebase-messaging.js");
const swScriptUrl = new URL(self.location);
const base64Config = swScriptUrl.searchParams.get('firebaseConfig')
let decoded = atob(base64Config);
const firebaseConfig = JSON.parse(decoded);
const app = firebase.initializeApp(firebaseConfig);
// Retrieve an instance of Firebase Messaging so that it can handle background
const messaging = firebase.messaging();

Javascript Browser Amazon Cognito Username/Password Login Require Issue

Goal:
Use credentials located in Amazon Cognito to successfully login using Javascript in a Google Chrome browser session.
Problem:
Using the amazon cognito js package, I have been trying to get amazon cognito implemented in my Javascript so I can do a simple call.
I get the following error in my console.
require.js:5 GET file:///C:/path/amazon-cognito-identity-js.js net::ERR_FILE_NOT_FOUND
req.load # require.js:5
load # require.js:5
load # require.js:5
fetch # require.js:5
check # require.js:5
enable # require.js:5
enable # require.js:5
(anonymous) # require.js:5
(anonymous) # require.js:5
each # require.js:5
enable # require.js:5
init # require.js:5
(anonymous) # require.js:5
setTimeout (async)
req.nextTick # require.js:5
o # require.js:5
requirejs # require.js:5
(anonymous) # index.js:1
require.js:5 Uncaught Error: Script error for "amazon-cognito-identity-js"
http://requirejs.org/docs/errors.html#scripterror
at makeError (require.js:5:1067)
at HTMLScriptElement.onScriptError (require.js:5:13218)
I tried adding the package via npm install --save amazon-cognito-identity-js but it doesn't seem to register and not sure how to get it to register. Thoughts?
If no answer can be found, I'd be interested in setting up Amazon Cognito using Javascript as it has been a train wreck trying to figure this out. (I have done this on Swift and it was nowhere near this difficult).
Code:
webpack.config.js
module.exports = {
entry: './index.js',
output: {
path: __dirname + '/dist',
filename: 'my-app.js'
}
}
index.js
var AmazonCognitoIdentity = require(['amazon-cognito-identity-js']);
function signIn() {
console.log("Signing In");
var authenticationData = {
Username: '<username>',
Password: '<password>',
};
var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(
authenticationData
);
var poolData = {
UserPoolId: '<poolID>', // Your user pool id here
ClientId: '<clientID>', // Your client id here
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
var userData = {
Username: '<name>',
Pool: userPool,
};
var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
var accessToken = result.getAccessToken().getJwtToken();
//POTENTIAL: Region needs to be set if not already set previously elsewhere.
AWS.config.region = '<region>';
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: '...', // your identity pool id here
Logins: {
// Change the key below according to the specific region your user pool is in.
'cognito-idp.us-east-1.amazonaws.com/us-east-1_9jpw8F8BS': result
.getIdToken()
.getJwtToken(),
},
});
//refreshes credentials using AWS.CognitoIdentity.getCredentialsForIdentity()
AWS.config.credentials.refresh(error => {
if (error) {
console.error(error);
} else {
// Instantiate aws sdk service objects now that the credentials have been updated.
// example: var s3 = new AWS.S3();
console.log('Successfully logged!');
}
});
},
onFailure: function (err) {
alert(err.message || JSON.stringify(err));
},
});
}
index.html
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Login</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.1066.0.min.js"></script>
<script src="https://requirejs.org/docs/release/2.3.5/minified/require.js"></script>
<script src="./src/index.js"></script>
</head>
<body>
<button onclick="signIn()">Press Me</button>
</body>
Without using require, try using import statements like below. Below code snippet worked for me
import {
CognitoUserPool,
CognitoUser,
AuthenticationDetails,
} from "amazon-cognito-identity-js";
const login = () => {
const userPool = new CognitoUserPool({
UserPoolId: // userPoolID,
ClientId: // clientID,
});
const cognitoUser = new CognitoUser({
Username: // email,
Pool: userPool,
});
const authenticationDetails = new AuthenticationDetails({
Username: // email,
Password: // password,
});
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: (result) => {
// const accessToken = result.getAccessToken().getJwtToken();
cognitoUser.getUserAttributes(function (err, result) {
if (err) {
console.log("err", err);
return;
}
console.log("name",result[2].Value)
console.log("login success")
});
},
onFailure: (err) => {
console.log("login failed", err);
// reject(err);
},
});
}
Below article would be helpful for you to get a better understanding on this amazon-cognito-identity-js package.
https://medium.com/#sankharathnayaka/aws-cognito-authentication-without-using-amplify-8d0e3af997c2

reactjs axios post request throwing error

I have a function that gets data from a form when it is submitted and I am trying to make a post request using axios with this data here is my function (reactjs):
const handelSubmit = (e) => {
e.preventDefault();
const newFact = {Email, Fact, Source};
axios.post('https://www.examplesite.com/create', {
"data": newFact})
.then(function (response) {
console.log(response);
})
}
here's part of the code for the example site (nodejs):
const app = express();
app.use(express.json());
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type,
Accept');
next();
});
app.get("/", async function(req, res) {
const result = await randomfact();
res.send(result);
console.log(randomfact());
});
app.post('/create', function(req, res) {
console.log(req.body);
});
let port = process.env.PORT;
if(port == null || port == "") {
port = 8000;
}
app.listen(port, function() {
console.log("Server started successfully");
});
my problem is that the post request doesn't seem to be making it to the example site here's the error I got:
VM2633:1 POST https://www.examplesite.com/create net::ERR_NAME_NOT_RESOLVED
(anonymous) # VM2633:1
dispatchXhrRequest # xhr.js:177
xhrAdapter # xhr.js:13
dispatchRequest # dispatchRequest.js:52
Promise.then (async)
request # Axios.js:61
Axios.<computed> # Axios.js:87
wrap # bind.js:9
handelSubmit # Modal.js:14
callCallback # react-dom.development.js:3945
invokeGuardedCallbackDev # react-dom.development.js:3994
invokeGuardedCallback # react-dom.development.js:4056
invokeGuardedCallbackAndCatchFirstError # react-dom.development.js:4070
executeDispatch # react-dom.development.js:8243
processDispatchQueueItemsInOrder # react-dom.development.js:8275
processDispatchQueue # react-dom.development.js:8288
dispatchEventsForPlugins # react-dom.development.js:8299
(anonymous) # react-dom.development.js:8508
batchedEventUpdates$1 # react-dom.development.js:22396
batchedEventUpdates # react-dom.development.js:3745
dispatchEventForPluginEventSystem # react-dom.development.js:8507
attemptToDispatchEvent # react-dom.development.js:6005
dispatchEvent # react-dom.development.js:5924
unstable_runWithPriority # scheduler.development.js:468
runWithPriority$1 # react-dom.development.js:11276
discreteUpdates$1 # react-dom.development.js:22413
discreteUpdates # react-dom.development.js:3756
dispatchDiscreteEvent # react-dom.development.js:5889
createError.js:16 Uncaught (in promise) Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:84)
createError.js:16 Uncaught (in promise) Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:84)

Angular 7 CRUD App Service not connecting to REST Api

I'm trying to build an Angular 7 CRUD app with a REST Api following this tutorial.
Simply put it's a classic display products , add , edit and all that jazz kinda app.
The Rest API is made using Mongoose, Express and Node. Both the Angular App and the server are running fine on their own.
When I use mongod in the cmd it's waiting for an answer , and with the npm start in the api it does connect successfully.
Everything about the App works too without compilation errors.
But the app doesn't seem to be connected to the api at all , when I try to add a product to the empty list it just keeps on loading without going any further.
This is the service typescript file that I have :
import { Injectable } from '#angular/core';
import { Observable, of, throwError } from 'rxjs';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '#angular/common/http';
import { catchError, tap, map } from 'rxjs/operators';
import { Product } from './products';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
const apiUrl = "/api/v1/products";
#Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http: HttpClient) { }
private handleError<T>(operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
// TODO: send the error to remote logging infrastructure
console.error(error); // log to console instead
// Let the app keep running by returning an empty result.
return of(result as T);
};
}
getProducts(): Observable<Product[]> {
return this.http.get<Product[]>(apiUrl)
.pipe(
tap(heroes => console.log('fetched products')),
catchError(this.handleError('getProducts', []))
);
}
getProduct(id: number): Observable<Product> {
const url = `${apiUrl}/${id}`;
return this.http.get<Product>(url).pipe(
tap(_ => console.log(`fetched product id=${id}`)),
catchError(this.handleError<Product>(`getProduct id=${id}`))
);
}
addProduct(product): Observable<Product> {
return this.http.post<Product>(apiUrl, product, httpOptions).pipe(
tap((product: Product) => console.log(`added product w/ id=${product._id}`)),
catchError(this.handleError<Product>('addProduct'))
);
}
updateProduct(id, product): Observable<any> {
const url = `${apiUrl}/${id}`;
return this.http.put(url, product, httpOptions).pipe(
tap(_ => console.log(`updated product id=${id}`)),
catchError(this.handleError<any>('updateProduct'))
);
}
deleteProduct(id): Observable<Product> {
const url = `${apiUrl}/${id}`;
return this.http.delete<Product>(url, httpOptions).pipe(
tap(_ => console.log(`deleted product id=${id}`)),
catchError(this.handleError<Product>('deleteProduct'))
);
}
}
This is the app.js file for the api:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var restful = require('node-restful');
var methodOverride = require('method-override');
var cors = require('cors');
var index = require('./routes/index');
var users = require('./routes/users');
var products = require('./routes/products');
var app = express();
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/product')
.then(() => console.log('connection successful'))
.catch((err) => console.error(err));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(bodyParser.json({type:'application/vnd.api+json'}));
app.use(methodOverride());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(cors());
app.use('/', index);
app.use('/users', users);
app.use('/api/v1/products', products);
var Category = app.resource = restful.model('category', mongoose.Schema({
cat_name: String,
}))
.methods(['get', 'post', 'put', 'delete']);
Category.register(app, '/category');
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.json(err.message);
});
module.exports = app;
I don't have any error report to share at the moment, if you need more from the code I'll provide it as soon as I can.
Thanks in advance !
EDIT : The product-add component where I call the service :
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { ApiService } from '../api.service';
import { FormControl, FormGroupDirective, FormBuilder, FormGroup, NgForm, Validators } from '#angular/forms';
#Component({
selector: 'app-product-add',
templateUrl: './product-add.component.html',
styleUrls: ['./product-add.component.css']
})
export class ProductAddComponent implements OnInit {
productForm: FormGroup;
prod_name: string = '';
prod_desc: string = '';
prod_price: number = null;
updated_at: Date = null;
isLoadingResults = false;
onFormSubmit(form: NgForm) {
this.isLoadingResults = true;
this.api.addProduct(form)
.subscribe(res => {
let id = res['_id'];
this.isLoadingResults = false;
this.router.navigate(['/product-details', id]);
}, (err) => {
console.log(err);
this.isLoadingResults = false;
});
}
constructor(private router: Router, private api: ApiService, private formBuilder: FormBuilder) { }
ngOnInit() {
this.productForm = this.formBuilder.group({
'prod_name': [null, Validators.required],
'prod_desc': [null, Validators.required],
'prod_price': [null, Validators.required],
'updated_at': [null, Validators.required]
});
}
}
EDIT 2 : Some error logs that I didn't find at first , when accessing the app and it's trying to display a list from the server :
Angular is running in the development mode. Call enableProdMode() to enable the production mode.
zone.js:2969 GET http://localhost:4200/api/v1/products 404 (Not Found)
scheduleTask # zone.js:2969
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask # zone.js:407
onScheduleTask # zone.js:297
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask # zone.js:401
push../node_modules/zone.js/dist/zone.js.Zone.scheduleTask # zone.js:232
push../node_modules/zone.js/dist/zone.js.Zone.scheduleMacroTask # zone.js:255
scheduleMacroTaskWithCurrentZone # zone.js:1114
(anonymous) # zone.js:3001
proto.(anonymous function) # zone.js:1394
(anonymous) # http.js:1630
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe # Observable.js:43
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe # Observable.js:29
(anonymous) # subscribeTo.js:21
subscribeToResult # subscribeToResult.js:11
push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._innerSub # mergeMap.js:74
push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._tryNext # mergeMap.js:68
push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._next # mergeMap.js:51
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next # Subscriber.js:54
(anonymous) # scalar.js:5
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe # Observable.js:43
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe # Observable.js:29
push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapOperator.call # mergeMap.js:29
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe # Observable.js:24
push../node_modules/rxjs/_esm5/internal/operators/filter.js.FilterOperator.call # filter.js:15
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe # Observable.js:24
push../node_modules/rxjs/_esm5/internal/operators/map.js.MapOperator.call # map.js:18
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe # Observable.js:24
push../node_modules/rxjs/_esm5/internal/operators/tap.js.DoOperator.call # tap.js:18
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe # Observable.js:24
push../node_modules/rxjs/_esm5/internal/operators/catchError.js.CatchOperator.call # catchError.js:18
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe # Observable.js:24
push../src/app/products/products.component.ts.ProductsComponent.ngOnInit # products.component.ts:20
checkAndUpdateDirectiveInline # core.js:18668
checkAndUpdateNodeInline # core.js:19932
checkAndUpdateNode # core.js:19894
debugCheckAndUpdateNode # core.js:20528
debugCheckDirectivesFn # core.js:20488
(anonymous) # ProductsComponent_Ho…gfactory.js? [sm]:1
debugUpdateDirectives # core.js:20480
checkAndUpdateView # core.js:19876
callViewAction # core.js:20117
execEmbeddedViewsAction # core.js:20080
checkAndUpdateView # core.js:19877
callViewAction # core.js:20117
execComponentViewsAction # core.js:20059
checkAndUpdateView # core.js:19882
callWithDebugContext # core.js:20770
debugCheckAndUpdateView # core.js:20448
push../node_modules/#angular/core/fesm5/core.js.ViewRef_.detectChanges # core.js:18257
(anonymous) # core.js:14919
push../node_modules/#angular/core/fesm5/core.js.ApplicationRef.tick # core.js:14919
(anonymous) # core.js:14810
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke # zone.js:388
onInvoke # core.js:14191
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke # zone.js:387
push../node_modules/zone.js/dist/zone.js.Zone.run # zone.js:138
push../node_modules/#angular/core/fesm5/core.js.NgZone.run # core.js:14105
next # core.js:14810
schedulerFn # core.js:10206
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub # Subscriber.js:196
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next # Subscriber.js:134
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next # Subscriber.js:77
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next # Subscriber.js:54
push../node_modules/rxjs/_esm5/internal/Subject.js.Subject.next # Subject.js:47
push../node_modules/#angular/core/fesm5/core.js.EventEmitter.emit # core.js:10190
checkStable # core.js:14160
onHasTask # core.js:14204
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.hasTask # zone.js:441
push../node_modules/zone.js/dist/zone.js.ZoneDelegate._updateTaskCount # zone.js:461
push../node_modules/zone.js/dist/zone.js.Zone._updateTaskCount # zone.js:285
push../node_modules/zone.js/dist/zone.js.Zone.runTask # zone.js:205
drainMicroTaskQueue # zone.js:595
Promise.then (async)
scheduleMicroTask # zone.js:578
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask # zone.js:410
push../node_modules/zone.js/dist/zone.js.Zone.scheduleTask # zone.js:232
push../node_modules/zone.js/dist/zone.js.Zone.scheduleMicroTask # zone.js:252
scheduleResolveOrReject # zone.js:862
ZoneAwarePromise.then # zone.js:962
push../node_modules/#angular/core/fesm5/core.js.PlatformRef.bootstrapModule # core.js:14691
./src/main.ts # main.ts:12
__webpack_require__ # bootstrap:78
0 # main.ts:13
__webpack_require__ # bootstrap:78
checkDeferredModules # bootstrap:45
webpackJsonpCallback # bootstrap:32
(anonymous) # main.js:1
api.service.ts:22
HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: "Not Found", url: "http://localhost:4200/api/v1/products", ok: false, …}
error: "<!DOCTYPE html>↵<html lang="en">↵<head>↵<meta charset="utf-8">↵<title>Error</title>↵</head>↵<body>↵<pre>Cannot GET /api/v1/products</pre>↵</body>↵</html>↵"
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure response for http://localhost:4200/api/v1/products: 404 Not Found"
name: "HttpErrorResponse"
ok: false
status: 404
statusText: "Not Found"
url: "http://localhost:4200/api/v1/products"
__proto__: HttpResponseBase
Also the one I get when I try to add a new product :
zone.js:2969 POST http://localhost:4200/api/v1/products 404 (Not Found)
scheduleTask # zone.js:2969
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask # zone.js:407
onScheduleTask # zone.js:297
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask # zone.js:401
push../node_modules/zone.js/dist/zone.js.Zone.scheduleTask # zone.js:232
push../node_modules/zone.js/dist/zone.js.Zone.scheduleMacroTask # zone.js:255
scheduleMacroTaskWithCurrentZone # zone.js:1114
(anonymous) # zone.js:3001
proto.(anonymous function) # zone.js:1394
(anonymous) # http.js:1630
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe # Observable.js:43
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe # Observable.js:29
(anonymous) # subscribeTo.js:21
subscribeToResult # subscribeToResult.js:11
push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._innerSub # mergeMap.js:74
push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._tryNext # mergeMap.js:68
push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._next # mergeMap.js:51
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next # Subscriber.js:54
(anonymous) # scalar.js:5
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe # Observable.js:43
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe # Observable.js:29
push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapOperator.call # mergeMap.js:29
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe # Observable.js:24
push../node_modules/rxjs/_esm5/internal/operators/filter.js.FilterOperator.call # filter.js:15
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe # Observable.js:24
push../node_modules/rxjs/_esm5/internal/operators/map.js.MapOperator.call # map.js:18
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe # Observable.js:24
push../node_modules/rxjs/_esm5/internal/operators/tap.js.DoOperator.call # tap.js:18
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe # Observable.js:24
push../node_modules/rxjs/_esm5/internal/operators/catchError.js.CatchOperator.call # catchError.js:18
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe # Observable.js:24
push../src/app/product-add/product-add.component.ts.ProductAddComponent.onFormSubmit # product-add.component.ts:23
(anonymous) # ProductAddComponent.html:10
handleEvent # core.js:19676
callWithDebugContext # core.js:20770
debugHandleEvent # core.js:20473
dispatchEvent # core.js:17125
(anonymous) # core.js:18615
schedulerFn # core.js:10218
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub # Subscriber.js:196
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next # Subscriber.js:134
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next # Subscriber.js:77
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next # Subscriber.js:54
push../node_modules/rxjs/_esm5/internal/Subject.js.Subject.next # Subject.js:47
push../node_modules/#angular/core/fesm5/core.js.EventEmitter.emit # core.js:10190
push../node_modules/#angular/forms/fesm5/forms.js.FormGroupDirective.onSubmit # forms.js:4647
(anonymous) # ProductAddComponent.html:10
handleEvent # core.js:19676
callWithDebugContext # core.js:20770
debugHandleEvent # core.js:20473
dispatchEvent # core.js:17125
(anonymous) # core.js:17572
(anonymous) # platform-browser.js:993
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask # zone.js:421
onInvokeTask # core.js:14182
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask # zone.js:420
push../node_modules/zone.js/dist/zone.js.Zone.runTask # zone.js:188
push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask # zone.js:496
invokeTask # zone.js:1540
globalZoneAwareCallback # zone.js:1566
api.service.ts:22 HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: "Not Found", url: "http://localhost:4200/api/v1/products", ok: false, …}
(anonymous) # api.service.ts:22
push../node_modules/rxjs/_esm5/internal/operators/catchError.js.CatchSubscriber.error # catchError.js:34
push../node_modules/rxjs/_esm5/internal/operators/tap.js.TapSubscriber._error # tap.js:61
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error # Subscriber.js:60
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error # Subscriber.js:80
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error # Subscriber.js:60
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error # Subscriber.js:80
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error # Subscriber.js:60
push../node_modules/rxjs/_esm5/internal/OuterSubscriber.js.OuterSubscriber.notifyError # OuterSubscriber.js:13
push../node_modules/rxjs/_esm5/internal/InnerSubscriber.js.InnerSubscriber._error # InnerSubscriber.js:18
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error # Subscriber.js:60
onLoad # http.js:1547
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask # zone.js:421
onInvokeTask # core.js:14182
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask # zone.js:420
push../node_modules/zone.js/dist/zone.js.Zone.runTask # zone.js:188
push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask # zone.js:496
invokeTask # zone.js:1540
globalZoneAwareCallback # zone.js:1566
error (async)
customScheduleGlobal # zone.js:1666
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask # zone.js:407
onScheduleTask # zone.js:297
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask # zone.js:401
push../node_modules/zone.js/dist/zone.js.Zone.scheduleTask # zone.js:232
push../node_modules/zone.js/dist/zone.js.Zone.scheduleEventTask # zone.js:258
(anonymous) # zone.js:1831
(anonymous) # http.js:1619
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe # Observable.js:43
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe # Observable.js:29
(anonymous) # subscribeTo.js:21
subscribeToResult # subscribeToResult.js:11
push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._innerSub # mergeMap.js:74
push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._tryNext # mergeMap.js:68
push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._next # mergeMap.js:51
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next # Subscriber.js:54
(anonymous) # scalar.js:5
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe # Observable.js:43
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe # Observable.js:29
push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapOperator.call # mergeMap.js:29
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe # Observable.js:24
push../node_modules/rxjs/_esm5/internal/operators/filter.js.FilterOperator.call # filter.js:15
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe # Observable.js:24
push../node_modules/rxjs/_esm5/internal/operators/map.js.MapOperator.call # map.js:18
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe # Observable.js:24
push../node_modules/rxjs/_esm5/internal/operators/tap.js.DoOperator.call # tap.js:18
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe # Observable.js:24
push../node_modules/rxjs/_esm5/internal/operators/catchError.js.CatchOperator.call # catchError.js:18
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe # Observable.js:24
push../src/app/product-add/product-add.component.ts.ProductAddComponent.onFormSubmit # product-add.component.ts:23
(anonymous) # ProductAddComponent.html:10
handleEvent # core.js:19676
callWithDebugContext # core.js:20770
debugHandleEvent # core.js:20473
dispatchEvent # core.js:17125
(anonymous) # core.js:18615
schedulerFn # core.js:10218
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub # Subscriber.js:196
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next # Subscriber.js:134
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next # Subscriber.js:77
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next # Subscriber.js:54
push../node_modules/rxjs/_esm5/internal/Subject.js.Subject.next # Subject.js:47
push../node_modules/#angular/core/fesm5/core.js.EventEmitter.emit # core.js:10190
push../node_modules/#angular/forms/fesm5/forms.js.FormGroupDirective.onSubmit # forms.js:4647
(anonymous) # ProductAddComponent.html:10
handleEvent # core.js:19676
callWithDebugContext # core.js:20770
debugHandleEvent # core.js:20473
dispatchEvent # core.js:17125
(anonymous) # core.js:17572
(anonymous) # platform-browser.js:993
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask # zone.js:421
onInvokeTask # core.js:14182
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask # zone.js:420
push../node_modules/zone.js/dist/zone.js.Zone.runTask # zone.js:188
push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask # zone.js:496
invokeTask # zone.js:1540
globalZoneAwareCallback # zone.js:1566
core.js:12632 ERROR TypeError: Cannot read property '_id' of undefined
at SafeSubscriber._next (product-add.component.ts:24)
at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub (Subscriber.js:196)
at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next (Subscriber.js:134)
at Subscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next (Subscriber.js:77)
at Subscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54)
at CatchSubscriber.push../node_modules/rxjs/_esm5/internal/OuterSubscriber.js.OuterSubscriber.notifyNext (OuterSubscriber.js:10)
at InnerSubscriber.push../node_modules/rxjs/_esm5/internal/InnerSubscriber.js.InnerSubscriber._next (InnerSubscriber.js:15)
at InnerSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54)
at subscribeTo.js:16
at subscribeToResult (subscribeToResult.js:11)
And the products.js file :
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Product = require('../models/Product.js');
/* GET ALL PRODUCTS */
router.get('/', function(req, res, next) {
Product.find(function (err, products) {
if (err) return next(err);
res.json(products);
});
});
/* GET SINGLE PRODUCT BY ID */
router.get('/:id', function(req, res, next) {
Product.findById(req.params.id, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* SAVE PRODUCT */
router.post('/', function(req, res, next) {
Product.create(req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* UPDATE PRODUCT */
router.put('/:id', function(req, res, next) {
Product.findByIdAndUpdate(req.params.id, req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* DELETE PRODUCT */
router.delete('/:id', function(req, res, next) {
Product.findByIdAndRemove(req.params.id, req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
module.exports = router;
This tutorial is not complete. The author was missing a very essential part: because we are in a development environment, usually our RESTful server and a client application running under localhost, but on different ports. To get it to communicate with each other, we need a simple proxy:
Create the proxy.conf.json in root (src) folder and insert the following code:
{
"/api/*": {
"target": "http://localhost:3000",
"secure": false,
"logLevel": "debug",
"changeOrigin": true
}
}
Replace "/api/*" and RESTful server port# with yours ":3000" and when starting Angular client, use this command:
ng serve --proxy-config proxy.conf.json
(For RESTful server: npm run start)
After applying these changes, the tutorial works ~ 90%!
DELETE API is not working and if I am not wrong, the request was not blocked by CORS, because in our case we already using a proxy. The API is working fine because, with Postman, I can delete the article. See the console error below:
zone-evergreen.js:2952 DELETE http://localhost:4200/api/article/5d336729fafe194efa7fb102 500 (Internal Server Error)
api.service.ts:20 HttpErrorResponse {headers: HttpHeaders, status: 500, statusText: "Internal Server Error", url: "http://localhost:4200/api/article/5d336729fafe194efa7fb102", ok: false, …}

Categories