reactjs axios post request throwing error - javascript

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)

Related

Internal server error 500 when making POST request to server

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!!!

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();

Conditional redirect is not working, how to redirect on successful registration?

I am using a login API and connecting it to my frontend. on successfulregistration i want my page to redirect to login after registration
I have tried many solutions. none worked. registration is happening successfully . log in console from API end :
registerAPI: { username: 'newuser3', password: 'newuser3',
redirect: false }
{ _id: 5d4276f958c094127f74a2f3,
username: 'newuser3',
password:
'$2a$10$okji6W0OzTIaE.sQXJAYv.ckcmuRYcHAjKB6Nr6m.HVdBksWYT70u',
hash: '$2a$10$okji6W0OzTIaE.sQXJAYv.' }
console in frontend :
Navigated to http://localhost:3000/signupemail?
VM602 bundle.js:59399 try registering : {username: "newuser3",
password: "newuser3", redirect: false}
2Navigated to http://localhost:3000/signupemail?
this is my constructor
constructor(props) {
super(props);
this.state = {
username: "",
password: "",
redirect: false
};
}
this is handle submit on form submit
handleSubmit = event => {
console.log("try registering : ", this.state);
axios
.post("http://localhost:3044/register", this.state)
.then(function(response) {
console.log(response.status);
if (response.status === 200) {
console.log("registered");
this.setState({
redirect: true
});
}
})
.catch(function(error) {
console.log(error);
});
};
this is first few lines of where i am rendering a registration form or redirect
render() {
if (this.state.redirect) {
return <Redirect to="/loginemail" />;
}
return (
// <Layout>
<div className="Login">
//rest of the form and divs (rendering perfectly ok)
<link
href="https://bootswatch.com/4/simplex/bootstrap.min.css"
rel="stylesheet"
/>
<div style={indivStyle}>
<h1> Sign up with email </h1>
<br />
{/* <p
style={{
fontSize: "16px",
paddingRight: "10px",
paddingLeft: "10px"
}}
>
Enter the email address associated with your account, and we’ll send
a magic link to your inbox.
</p> */}
<div
style={{
padding: "15px",
marginRight: "60px",
marginLeft: "60px"
}}
>
<p
style={{
color: "grey",
fontSize: "12px",
paddingRight: "10px",
paddingLeft: "10px"
}}
>
Your username
</p>
<div className="form-group">
<form onSubmit={this.handleSubmit}>
<input
type="text"
onChange={this.handleUnameChange}
className="form-control"
style={{ border: "none", borderBottom: "1px solid" }}
/>
<br />
<br />
<p
style={{
color: "grey",
fontSize: "12px",
paddingRight: "10px",
paddingLeft: "10px"
}}
>
Password
</p>
<input
type="text"
onChange={this.handlePassChange}
className="form-control"
style={{ border: "none", borderBottom: "1px solid" }}
/>
<br />
<button
type="submit"
style={{
color: "white",
backgroundColor: "black",
borderColor: "black"
}}
className="btn btn-lg "
>
Continue
</button>
</form>
</div>
<div>{this.state.redir}</div>
<br />
<p style={{ fontSize: "13px" }}>
<Link style={{ color: "teal" }} to="/getstarted">
← All sign up options
</Link>
</p>
</div>
</div>
</div>
);
}
expecting to render login
request : is called twice. first with status : 200, second with status : "canceled"
two instances :
Request URL: http://localhost:3044/register
Referrer Policy: no-referrer-when-downgrade
Provisional headers are shown
Accept: application/json, text/plain, */*
Content-Type: application/json;charset=UTF-8
Origin: http://localhost:3000
Referer: http://localhost:3000/signupemail?
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML,
like Gecko) Chrome/75.0.3770.142 Safari/537.36
{username: "", password: "", redirect: false}
password: ""
redirect: false
username: ""
first request call :
Request URL: http://localhost:3044/register
Request Method: OPTIONS
Status Code: 200 OK
Remote Address: [::1]:3044
Referrer Policy: no-referrer-when-downgrade
second request call : (not sure why it gets called twice)
Request URL: http://localhost:3044/register
Referrer Policy: no-referrer-when-downgrade
Provisional headers are shown
Accept: application/json, text/plain, */*
Content-Type: application/json;charset=UTF-8
Origin: http://localhost:3000
Referer: http://localhost:3000/signupemail?
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML,
like Gecko) Chrome/75.0.3770.142 Safari/537.36
{username: "Newuser14", password: "newuser14", redirect: false}
password: "newuser14"
redirect: false
username: "Newuser14"
some more logs :
logs(){
VM3928 bundle.js:26 XHR finished loading: GET
"http://localhost:3000/b9fefce4d0ef18cb1a0b.hot-update.json".
hotDownloadManifest # VM3928 bundle.js:26
hotCheck # VM3928 bundle.js:245
tryApplyUpdates # VM3928 bundle.js:911
handleSuccess # VM3928 bundle.js:782
connection.onmessage # VM3928 bundle.js:855
EventTarget.dispatchEvent # VM3928 bundle.js:3007
(anonymous) # VM3928 bundle.js:6216
SockJS._transportMessage # VM3928 bundle.js:6214
EventEmitter.emit # VM3928 bundle.js:2942
(anonymous) # VM3928 bundle.js:3170
EventEmitter.emit # VM3928 bundle.js:2942
(anonymous) # VM3928 bundle.js:3327
EventEmitter.emit # VM3928 bundle.js:294
XhrReceiver._chunkHandler # VM3928 bundle.js:3412
EventEmitter.emit # VM3928 bundle.js:2942
xhr.onreadystatechange # VM3928 bundle.js:3569
XMLHttpRequest.send (async)
AbstractXHRObject._start # VM3928 bundle.js:3594
(anonymous) # VM3928 bundle.js:3487
setTimeout (async)
AbstractXHRObject # VM3928 bundle.js:3486
AbstractXHRObject._start # abstract-xhr.js:128
(anonymous) # abstract-xhr.js:21
setTimeout (async)
AbstractXHRObject # abstract-xhr.js:20
XHRLocalObject # xhr-local.js:8
InfoAjax # info-ajax.js:19
InfoReceiver._getReceiver # info-receiver.js:36
InfoReceiver.doXhr # info-receiver.js:56
(anonymous) # info-receiver.js:25
setTimeout (async)
InfoReceiver # info-receiver.js:24
SockJS # main.js:122
(anonymous) # webpackHotDevClient.js:142
__webpack_require__ # bootstrap 4820ba57e6e007595bd9:555
fn # bootstrap 4820ba57e6e007595bd9:86
(anonymous) # bootstrap 4820ba57e6e007595bd9:578
__webpack_require__ # bootstrap 4820ba57e6e007595bd9:555
(anonymous) # bootstrap 4820ba57e6e007595bd9:578
(anonymous) # bootstrap 4820ba57e6e007595bd9:578
XHRCorsObject # VM3928 bundle.js:3450
XhrReceiver # VM3928 bundle.js:3382
Polling._scheduleReceiver # VM3928 bundle.js:3323
Polling # VM3928 bundle.js:3315
SenderReceiver # VM3928 bundle.js:3167
AjaxBasedTransport # VM3928 bundle.js:3133
XhrStreamingTransport # VM3928 bundle.js:3053
SockJS._connect # VM3928 bundle.js:6161
SockJS._transportClose # VM3928 bundle.js:6241
SockJS._transportTimeout # VM3928 bundle.js:6175
setTimeout (async)
SockJS._connect # VM3928 bundle.js:6156
SockJS._receiveInfo # VM3928 bundle.js:6136
g # VM3928 bundle.js:2928
EventEmitter.emit # VM3928 bundle.js:2942
(anonymous) # VM3928 bundle.js:7121
g # VM3928 bundle.js:2928
EventEmitter.emit # VM3928 bundle.js:2942
(anonymous) # VM3928 bundle.js:7343
g # VM3928 bundle.js:2928
EventEmitter.emit # VM3928 bundle.js:2942
xhr.onreadystatechange # VM3928 bundle.js:3586
XMLHttpRequest.send (async)
AbstractXHRObject._start # VM3928 bundle.js:3594
(anonymous) # VM3928 bundle.js:3487
setTimeout (async)
AbstractXHRObject # VM3928 bundle.js:3486
XHRLocalObject # VM3928 bundle.js:3669
InfoAjax # VM3928 bundle.js:7325
InfoReceiver._getReceiver # VM3928 bundle.js:7090
InfoReceiver.doXhr # VM3928 bundle.js:7110
(anonymous) # VM3928 bundle.js:7079
setTimeout (async)
InfoReceiver # VM3928 bundle.js:7078
SockJS # VM3928 bundle.js:6064
(anonymous) # VM3928 bundle.js:742
__webpack_require__ # VM3928 bundle.js:556
fn # VM3928 bundle.js:87
(anonymous) # VM3928 bundle.js:589
__webpack_require__ # VM3928 bundle.js:556
(anonymous) # VM3928 bundle.js:579
(anonymous) # VM3928 bundle.js:582
VM3928 bundle.js:3594 XHR failed loading: POST "http://localhost:3000/sockjs-node/173/wjddrgzb/xhr_streaming?t=1564659551778".
AbstractXHRObject._start # VM3928 bundle.js:3594
(anonymous) # VM3928 bundle.js:3487
setTimeout (async)
AbstractXHRObject # VM3928 bundle.js:3486
XHRCorsObject # VM3928 bundle.js:3450
XhrReceiver # VM3928 bundle.js:3382
Polling._scheduleReceiver # VM3928 bundle.js:3323
Polling # VM3928 bundle.js:3315
SenderReceiver # VM3928 bundle.js:3167
AjaxBasedTransport # VM3928 bundle.js:3133
XhrStreamingTransport # VM3928 bundle.js:3053
SockJS._connect # VM3928 bundle.js:6161
SockJS._transportClose # VM3928 bundle.js:6241
SockJS._transportTimeout # VM3928 bundle.js:6175
setTimeout (async)
SockJS._connect # VM3928 bundle.js:6156
SockJS._receiveInfo # VM3928 bundle.js:6136
g # VM3928 bundle.js:2928
EventEmitter.emit # VM3928 bundle.js:2942
(anonymous) # VM3928 bundle.js:7121
g # VM3928 bundle.js:2928
EventEmitter.emit # VM3928 bundle.js:2942
(anonymous) # VM3928 bundle.js:7343
g # VM3928 bundle.js:2928
EventEmitter.emit # VM3928 bundle.js:2942
xhr.onreadystatechange # VM3928 bundle.js:3586
XMLHttpRequest.send (async)
AbstractXHRObject._start # VM3928 bundle.js:3594
(anonymous) # VM3928 bundle.js:3487
setTimeout (async)
AbstractXHRObject # VM3928 bundle.js:3486
XHRLocalObject # VM3928 bundle.js:3669
InfoAjax # VM3928 bundle.js:7325
InfoReceiver._getReceiver # VM3928 bundle.js:7090
InfoReceiver.doXhr # VM3928 bundle.js:7110
(anonymous) # VM3928 bundle.js:7079
setTimeout (async)
InfoReceiver # VM3928 bundle.js:7078
SockJS # VM3928 bundle.js:6064
(anonymous) # VM3928 bundle.js:742
__webpack_require__ # VM3928 bundle.js:556
fn # VM3928 bundle.js:87
(anonymous) # VM3928 bundle.js:589
__webpack_require__ # VM3928 bundle.js:556
(anonymous) # VM3928 bundle.js:579
(anonymous) # VM3928 bundle.js:582
Navigated to http://localhost:3000/signupemail
VM3945 bundle.js:3594 XHR finished loading: GET "http://localhost:3000/sockjs-node/info?t=1564659612053".
AbstractXHRObject._start # VM3945 bundle.js:3594
(anonymous) # VM3945 bundle.js:3487
setTimeout (async)
AbstractXHRObject # VM3945 bundle.js:3486
XHRLocalObject # VM3945 bundle.js:3669
InfoAjax # VM3945 bundle.js:7325
InfoReceiver._getReceiver # VM3945 bundle.js:7090
InfoReceiver.doXhr # VM3945 bundle.js:7110
(anonymous) # VM3945 bundle.js:7079
setTimeout (async)
InfoReceiver # VM3945 bundle.js:7078
SockJS # VM3945 bundle.js:6064
(anonymous) # VM3945 bundle.js:742
__webpack_require__ # VM3945 bundle.js:556
fn # VM3945 bundle.js:87
(anonymous) # VM3945 bundle.js:589
__webpack_require__ # VM3945 bundle.js:556
(anonymous) # VM3945 bundle.js:579
(anonymous) # VM3945 bundle.js:582
VM3945 bundle.js:59646 try registering : {username: "saloniuser", password: "saloniuser", redirect: false}
VM3945 bundle.js:61076 XHR finished loading: OPTIONS "http://localhost:3044/register".
dispatchXhrRequest # VM3945 bundle.js:61076
xhrAdapter # VM3945 bundle.js:60915
dispatchRequest # VM3945 bundle.js:60696
Promise.then (async)
request # VM3945 bundle.js:60454
Axios.<computed> # VM3945 bundle.js:60479
wrap # VM3945 bundle.js:60370
LoginEmail._this.handleSubmit # VM3945 bundle.js:59647
callCallback # VM3945 bundle.js:13280
invokeGuardedCallbackDev # VM3945 bundle.js:13330
invokeGuardedCallback # VM3945 bundle.js:13387
invokeGuardedCallbackAndCatchFirstError # VM3945 bundle.js:13401
executeDispatch # VM3945 bundle.js:13692
executeDispatchesInOrder # VM3945 bundle.js:13714
executeDispatchesAndRelease # VM3945 bundle.js:13811
executeDispatchesAndReleaseTopLevel # VM3945 bundle.js:13819
forEachAccumulated # VM3945 bundle.js:13793
runEventsInBatch # VM3945 bundle.js:13947
runExtractedEventsInBatch # VM3945 bundle.js:13955
handleTopLevel # VM3945 bundle.js:17957
batchedUpdates$1 # VM3945 bundle.js:33570
batchedUpdates # VM3945 bundle.js:15282
dispatchEvent # VM3945 bundle.js:18036
(anonymous) # VM3945 bundle.js:33621
unstable_runWithPriority # VM3945 bundle.js:34689
interactiveUpdates$1 # VM3945 bundle.js:33620
interactiveUpdates # VM3945 bundle.js:15301
dispatchInteractiveEvent # VM3945 bundle.js:18013
XHR failed loading: POST "http://localhost:3044/register".
Navigated to http://localhost:3000/signupemail?
abstract-xhr.js:128 XHR finished loading: GET "http://localhost:3000/sockjs-node/info?t=1564659645382".
}
"::1" is the ipv6 version of 127.0.0.1. May be the socket trying to connect with the IPV6 so make sure it is enabled.
Remote Address: [::1]:3044
While you're trying to set redirect as true using this.setState, try changing your handleSubmit function to this -
axios
.post("http://localhost:3044/register", this.state)
.then(response => { // change it to an arrow function
console.log(response.status);
if (response.status === 200) {
this.setState({
redirect: true
});
}
})
.catch(function(error) {
console.log(error);
});

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