Unable send data from backend(nodejs) to frontend(angular2) - node.js

I have some data which I queried from elasticsearch through nodejs and I want to send those to frontend. When I try to do that it shows me an error as below.
ERROR Error: Uncaught (in promise): Response with status: 0 for URL: null
at resolvePromise (zone.js:783)
at zone.js:709
at rejected (messages-component.js:14)
at ZoneDelegate.invoke (zone.js:391)
at Object.onInvoke (ng_zone.ts:296)
at ZoneDelegate.invoke (zone.js:390)
at Zone.run (zone.js:141)
at zone.js:831
at ZoneDelegate.invokeTask (zone.js:424)
at Object.onInvokeTask (ng_zone.ts:288)
Back-end looks like this,
var name = ".class";
rama();
function rama() {
'use strict';
const elasticsearch = require('elasticsearch');
const esClient = new elasticsearch.Client({
host: '127.0.0.1:9200',
log: 'error'
});
const search = function search(index, body) {
return esClient.search({index: index, body: body});
};
const test = function test() {
let body = {
size: 20,
from: 0,
query: {
match: {
JarFileName: {
query: 'CambioClient.jar'
}
}
}
};
search('clsdex', body)
.then(results => {
results.hits.hits.forEach((hit, index) => name="Test");
})
.catch(console.error);
};
test();
};
var express = require('express');
var app = express();
var messages = [{text: name, owner: 'Tim'},{text: 'other message', owner:'Jane'}];
app.use((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('/messages', (req, res) => {
res.json(messages);
})
app.listen(11500);
This is the part in front-end(message-component.ts) where I receiving the results,
import { Component } from '#angular/core';
import { WebService } from './web.service';
#Component({
selector: 'messages',
template: `
<div *ngFor="let message of messages">
<md-card style="margin:8px">
<md-card-title>{{message.owner}}</md-card-title>
<md-card-content>{{message.text}}</md-card-content>
</md-card>
</div>
`
})
export class MessagesComponent {
messages = [];
constructor(private webService: WebService) {}
async ngOnInit() {
var response = await this.webService.getMessages();
this.messages = response.json();
}
}
Where am I mistaken this? Please help me to figure it out.

Related

How to fetch data from backend using axios?

I have created a backend server using expressjs. I have created a frontend client using react. But I can't merge them both when am trying to get data from backend using axios am getting an error.
This is my index.js from backend
const express=require("express");
const mongoose=require("mongoose");
const dotenv=require("dotenv");
const helmet=require("helmet");
const morgan=require("morgan");
const UserRoute=require("./routes/users");
const AuthRoute=require("./routes/auth");
const PostRoute=require("./routes/posts");
const cors=require('cors');
const app=express();
dotenv.config();
mongoose.connect(process.env.MONGO_URL,{useNewUrlParser: true},()=>{
console.log("Database connected successfully!!")
});
//middleware
app.use(express.json());
app.use(helmet());
app.use(morgan("common"));
app.use(cors());
app.use("/api/user",UserRoute);
app.use("/api/auth",AuthRoute);
app.use("/api/post",PostRoute);
app.listen(8800,()=>console.log("server is running!!"));
This is my posts.js from backend server
const router = require("express").Router();
const User=require("../models/User");
const Post = require("../models/Post");
//create a post
router.post("/", async (req, res) => {
const newPost = new Post(req.body);
try {
const savedPost = await newPost.save();
res.status(200).json(newPost);
}
catch (err) {
res.status(500).json(err);
}
});
//update a post
router.post("/:id", async (req, res) => {
try {
const post = Post.findById(req.params.id);
if (req.params.id === req.body.userId) {
await post.updateOne({ $set: req.body });
res.status(200).json("The post has been updated!");
}
else {
res.status(403).json("You can update only your post!!");
}
}
catch (err) {
res.status(500).json(err);
}
});
//delete a post
router.post("/:id/delete", async (req, res) => {
try {
if (req.params.id === req.body.userId) {
await Post.findByIdAndDelete(req.params.id);
res.status(200).json("The post has been deleted!!");
}
else {
res.status(403).json("You can delete only your post!!");
}
}
catch (err) {
res.status(500).json(err);
}
});
//get a post
router.get("/:id", async (req, res) => {
try {
const post = await Post.findById(req.params.id);
res.status(200).json(post);
}
catch (err) {
res.status(500).json(err);
}
});
//like a post
router.put("/:id/like", async (req, res) => {
try {
const post = await Post.findById(req.params.id);
if (!post.likes.includes(req.body.userId)) {
await post.updateOne({ $push: { likes: req.body.userId } });
res.status(200).json("The post has been liked");
}
else {
await post.updateOne({ $pull: { likes: req.body.userId } });
res.status(200).json("The post has been disliked");
}
}
catch (err) {
res.status(500).json(err);
}
});
//timeline posts
router.get("/timeline/:userId", async (req, res) => {
try {
const currentUser = await User.findById(req.params.userId);
const userPosts = await Post.find({userId:currentUser._id} );
const friendPosts = await Promise.all(
currentUser.following.map(friendId => {
return Post.find({ userId: friendId });
})
);
res.status(200).json(userPosts.concat(...friendPosts));
}
catch (err) {
res.status(500).json(err);
}
})
module.exports = router;
This is my feed.js from frontend
import "./feed.css";
import Post from "../post/Post";
import Share from "../share/Share";
import { useState } from "react";
import { useEffect } from "react";
import axios from 'axios';
export default function Feed() {
const [posts,setPosts]=useState([]);
const [texts,setTexts]=useState([]);
useEffect(()=>{
const fetchPosts=async ()=>{
const res=await axios.get("post/timeline/63c29c2fe9a410383d4bcb98");
console.log(res);
};
fetchPosts();
},[])
return (
<div className="feed">
<div className="feedWrapper">
<Share/>
{/*{Posts.map((p)=>{
<Post key={p.id} post={p}/>
})}*/}
</div>
</div>
)
}
When I try to reload the react app it's showing this
GET http://locahost:8800/api/post/timeline/63c29c2fe9a410383d4bcb98 net::ERR_NAME_NOT_RESOLVED
dispatchXhrRequest # xhr.js:247
xhr # xhr.js:49
dispatchRequest # dispatchRequest.js:51
request # Axios.js:142
Axios.<computed> # Axios.js:168
wrap # bind.js:5
fetchPosts # Feed.jsx:13
(anonymous) # Feed.jsx:16
commitHookEffectListMount # react-dom.development.js:23150
commitPassiveMountOnFiber # react-dom.development.js:24926
commitPassiveMountEffects_complete # react-dom.development.js:24891
commitPassiveMountEffects_begin # react-dom.development.js:24878
commitPassiveMountEffects # react-dom.development.js:24866
flushPassiveEffectsImpl # react-dom.development.js:27039
flushPassiveEffects # react-dom.development.js:26984
(anonymous) # react-dom.development.js:26769
workLoop # scheduler.development.js:266
flushWork # scheduler.development.js:239
performWorkUntilDeadline # scheduler.development.js:533
Feed.jsx:15 Uncaught (in promise) AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}
Console Image
API URL is not valid, hostname should be localhost instead of locahost

Angular: Error while fetching data from Node API?

I am trying to fetch json data from my Nodejs API using URL - localhost:3000/articles/publicationData which is running successfully in Postman app but don't know why is giving error with same url in angular app, but in Angular app it is giving an error -
HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: "Not Found", url: "http://localhost:3000/articles/publicationData", ok: false, …}
error: "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>Cannot GET /articles/publicationData</pre>\n</body>\n</html>\n"
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure response for http://localhost:3000/articles/publicationData: 404 Not Found"
name: "HttpErrorResponse"
ok: false
status: 404
statusText: "Not Found"
url: "http://localhost:3000/articles/publicationData"
My app-service.ts file is -
import { Injectable } from '#angular/core';
import { HttpClient} from '#angular/common/http';
import { AppSetting } from './appsetting'
#Injectable({
providedIn: 'root'
})
export class AppServiceService {
private SERVERURL = AppSetting.API;
constructor(private http: HttpClient) { }
login(user){
console.log(user);
return this.http.post<any>(this.SERVERURL+"users",user);
}
getPublication(){
let url = "http://localhost:3000/articles/publicationData";
return this.http.get(url);
}
}
My app.component.ts file
import { Component, OnInit } from '#angular/core';
import { DatepickerModule } from 'ng2-datepicker';
import { HttpClient } from '#angular/common/http';
import { Router } from '#angular/router';
import { DatepickerOptions } from 'ng2-datepicker';
import { AppServiceService } from './../app-service.service';
import { Subscriber } from 'rxjs';
#Component({
selector: 'app-main',
templateUrl: './main.component.html',
styleUrls: ['./main.component.css']
})
export class MainComponent implements OnInit {
constructor(private http: HttpClient,private auth : AppServiceService, private _router: Router) {
this.auth.getPublication().subscribe(data => {
console.warn(data);
})
}
ngOnInit(): void {
$("#menu-toggle").click(function(e) {
e.preventDefault();
$("#wrapper").toggleClass("toggled");
});
}
}
Controller.js
var db = require("../db.js");
var ObjectId = require('mongodb').ObjectID;
var mysql = require('mysql');
var connection = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'pass',
database: 'name'
});
var publicationData = (req, res) => {
var sql = `select pub_master.PubId, pub_master.Title,
pub_master.MastHead, pub_master.Circulation, pub_master.WebSite,
pub_master.Issn_Num, pub_master.Place, picklist.Name as city
from pub_master
join picklist on picklist.id = pub_master.Place
and picklist.id <> 0`;
connection.query(sql,[], function (error, results, fields) {
if (error) {
res.send({
"code":400,
"failed":"error ocurred"
})
}else{
if(results.length >0){
res.send({
"code":200,
result : results
});
}
else{
res.send({
"code":204,
"success":"Email and password does not match"
});
}
}
});
}
module.exports = {
publicationData: publicationData
}
Publication route
var express = require("express");
var articlescontroller = require("../controller/articlesController")
var articlesrouter = express.Router();
articlesrouter.route('/publicationData')
.post(articlescontroller.publicationData);
app.js
var express = require("express");
const serverless = require('serverless-http');
var moviesrouter = require("./routes/movierouter");
var articlesrouter = require("./routes/articlesrouter");
// var mailarticlerouter = require('./routes/mailarticlerouter');
var bodyParser = require("body-parser");
var mongoos = require("mongoose");
/*****************MYSQL CONNECTION*********************/
var mysql = require('mysql');
var connection = mysql.createPool({
host : '',
user : '',
password : '',
database : ''
});
/************************************* */
mongoos.set("debug", (collectionName, method, query, doc) => {
console.log(JSON.stringify(query));
});
mongoos.Promise = Promise;
var db = mongoos.connect("mongodb+srv://aamadmin:Rix2Jag8#irmpl-zame7.mongodb.net/impact?retryWrites=true&w=majority",{useUnifiedTopology: true,useNewUrlParser:true});
console.log("connected to mongodb");
var app = express();
var cors = require('cors');
const userrouter = require("./routes/userrouter");
app.use(cors());
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.use(bodyParser.json());
var server = app.listen(3000,()=>{
console.log("server is running on port 3000");
});
server.timeout = 600000;
module.exports.handler = serverless(app);
app.use('/articles',articlesrouter);
From your Postman screen, you need to send a POST request to localhost:3000/articles/publicationData, not a GET request. You have the 404 error with your code and when trying to access localhost:3000/articles/publicationData in browser because you're sending GET requests.
In your Angular code, change from :
getPublication(){
let url = "http://localhost:3000/articles/publicationData";
return this.http.get(url);
}
to :
getPublication(){
let url = "http://localhost:3000/articles/publicationData";
return this.http.post(url, {});
}

React-Admin Pagination didn't work properly?

first of all take a look to the problem :pagination problem
I'm using react-admin for the first time, so i just was getting started and creating some small projects to practice before i integrate it to my real project.
so i'm using react for the front-end and nodejs with express middleware for the backend.
as far i know react-admin has a dataprovider so i created dataprovider.js file:
import { fetchUtils } from 'react-admin';
import { stringify } from 'query-string';
const apiUrl = 'http://localhost:5000';
const httpClient = fetchUtils.fetchJson;
export default {
getList: (resource, params) => {
const { page, perPage } = params.pagination;
const { field, order } = params.sort;
const query = {
sort: JSON.stringify([field, order]),
range: JSON.stringify([(page - 1) * perPage, page * perPage - 1]),
filter: JSON.stringify(params.filter),
};
const url = `${apiUrl}/${resource}?${stringify(query)}`;
httpClient(url).then(({ headers, json }) => {
console.log(headers.get('content-range'))
console.log(json)
});
return httpClient(url).then(({ headers, json }) => ({
data: json.map((resource)=>({...resource, id:resource._id})),
total: parseInt(headers.get('content-range').split('/').pop(), 10),
}));
},
getOne: (resource, params) =>
httpClient(`${apiUrl}/${resource}/${params.id}`).then(({ json }) => ({
data: json,
})),
getMany: (resource, params) => {
const query = {
filter: JSON.stringify({ id: params.ids }),
};
const url = `${apiUrl}/${resource}?${stringify(query)}`;
return httpClient(url).then(({ json }) => ({ data: json }));
},
getManyReference: (resource, params) => {
const { page, perPage } = params.pagination;
const { field, order } = params.sort;
const query = {
sort: JSON.stringify([field, order]),
range: JSON.stringify([(page - 1) * perPage, page * perPage - 1]),
filter: JSON.stringify({
...params.filter,
[params.target]: params.id,
}),
};
const url = `${apiUrl}/${resource}?${stringify(query)}`;
return httpClient(url).then(({ headers, json }) => ({
data: json,
total: parseInt(headers.get('content-range').split('/').pop(), 10),
}));
},
update: (resource, params) =>
httpClient(`${apiUrl}/${resource}/${params.id}`, {
method: 'PUT',
body: JSON.stringify(params.data),
}).then(({ json }) => ({ data: json })),
updateMany: (resource, params) => {
const query = {
filter: JSON.stringify({ id: params.ids}),
};
return httpClient(`${apiUrl}/${resource}?${stringify(query)}`, {
method: 'PUT',
body: JSON.stringify(params.data),
}).then(({ json }) => ({ data: json }));
},
create: (resource, params) =>
httpClient(`${apiUrl}/${resource}`, {
method: 'POST',
body: JSON.stringify(params.data),
}).then(({ json }) => ({
data: { ...params.data, id: json.id },
})),
delete: (resource, params) =>
httpClient(`${apiUrl}/${resource}/${params.id}`, {
method: 'DELETE',
}).then(({ json }) => ({ data: json })),
deleteMany: (resource, params) => {
const query = {
filter: JSON.stringify({ id: params.ids}),
};
return httpClient(`${apiUrl}/${resource}?${stringify(query)}`, {
method: 'DELETE',
}).then(({ json }) => ({ data: json }));
}
};
and the App component which contains Admin:
import * as React from "react";
import { Admin, Resource } from 'react-admin';
import dataProvider from './DataProvider'
import { Products } from "./Products";
const App=()=> {
return (
<div className="App">
<Admin dataProvider={dataProvider}>
<Resource name='Products' list={Products} />
</Admin>
</div>
);
}
export default App;
and this is the products component:
import * as React from "react";
import { List, Datagrid, TextField, EditButton } from 'react-admin';
export const Products = props => (
<List {...props}>
<Datagrid rowClick="edit">
<TextField source='id'/>
<TextField source="Title" />
<TextField source='Brand'/>
<EditButton />
</Datagrid>
</List>
);
--------------------Backend:Nodejs -- expressjs ------------------------------------
and this is my simple server that return products from the database:
const express = require('express')
const app = express()
const port = 5000
var MongoClient = require("mongodb").MongoClient;
const { ObjectId } = require("mongodb"); // or ObjectID
var url = "mongodb://localhost:27017/storedz";
var db;
var storedz;
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", req.header("Origin"));
res.header("Access-Control-Allow-Credentials", true);
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
res.header("Access-Control-Expose-Headers", "Content-Range");
res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
next();
});
MongoClient.connect(url, function (err, database) {
if (err) throw err;
db = database;
storedz = db.db("storedz");
});
app.get('/Products',(req, res) => {
storedz
.collection("products")
.find({})
.toArray((err, result) => {
if (err) {
return res.header(400).json("something went wrong");
}
res.header("Content-Range", `getProducts 0-4/${result.length}`);
console.log(result.length)
res.send(result);
});
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
so everything is working i mean i'm getting all the products, and i u res.header("Content-Range", Products 0-4/${result.length}); because react-admin need it to make the pagination.
so guys if i'm missing something here please correct me and give the right path so i can move to my next step.
thank you.

Unexepected token U in JSON at position 0

I have a problem with MEAN Stack.
I have an Angular Form with good values to creat a company id DB with Node Express in backend. I have an error that the JSON in Node is Undefined. but i don't understand why ?
app.js
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const userboRoutes = require('./routes/userbo');
const companyRoutes = require('./routes/company');
const path = require('path');
mongoose.connect('mongodb://127.0.0.1/aya', {useNewUrlParser: true})
.then(() => {
console.log('Successfully connected to MongoDB AYA!');
})
.catch((error) => {
console.log('Unable to connect to MongoDB! AYA');
console.error(error);
});
const app = express();
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content, Accept, Content-Type, Authorization');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
next();
});
app.use(bodyParser.json());
app.use('/api/company', companyRoutes);
app.use('/api/authbo', userboRoutes);
module.exports = app;
routes\company.js
const express = require('express');
const router = express.Router();
const companyCtrl = require('../controllers/company');
const Company = require('../models/company');
router.post('/', companyCtrl.createCompany);
router.get('/:id', companyCtrl.getOneCompany);
router.put('/:id', companyCtrl.modifyCompany);
router.delete('/:id', companyCtrl.deleteCompany);
router.get('/', companyCtrl.getAllCompany);
module.exports = router;
controller\company.js
const Company = require('../models/company');
const fs = require('fs');
exports.createCompany = (req, res, next) => {
req.body.company = JSON.parse(req.body.company);
const company = new Company({
coid:req.body.company.coid,
coname: req.body.company.coname,
service: req.body.company.service,
address: req.body.company.address,
state: req.body.company.state,
zip: req.body.company.zip,
city: req.body.company.city,
country: req.body.company.country,
size: req.body.company.size,
domain: req.body.company.domain,
duns: req.body.company.duns,
tid1: req.body.company.tid1,
numid1: req.body.company.numid1,
tid2: req.body.company.tid2,
numid2: req.body.company.numid2,
tid3: req.body.company.tid3,
numid3: req.body.company.numid3,
bankname: req.body.company.bankname,
bicswift: req.body.company.bicswift,
iban: req.body.company.iban,
datecreat: req.body.company.datecreat,
bogid: req.body.company.bogid
});
company.save().then(
() => {
res.status(201).json({
message: 'Post saved successfully!'
});
}
).catch(
(error) => {
res.status(400).json({
error: error
});
}
);
};
Angular Component :
this.companyService.CreateCoData(company).then(
() => {
this.CreateCoForm.reset();
this.router.navigate(['home']);
},
(error)=> {
this.loading = false;
this.errorMessage = error.message;
}
);
Company service
import { Router } from '#angular/router';
import { Company } from './../models/company.model';
import { HttpClient, HttpClientModule } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Subject } from 'rxjs';
export class CompanyService {
constructor(private router: Router,
private http: HttpClient) { }
company: Company[];
companySubject = new Subject<Company[]>();
public company$ = new Subject<Company[]>();
CreateCoData(company: Company) {
return new Promise((resolve, reject) => {
this.http.post('http://localhost:3000/api/company', company).subscribe(
(response) => {
resolve(response);
},
(error) => {
reject(error);
}
);
});
}
I got this error :
SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at exports.createCompany (E:\MEAN\BACKEND\controllers\company.js:7:29)
Or in the Request payload (Chrome dev tools network) the json is correct.
I don't understand why the req json in undefined ?
Please help me to understand :)
UPDATE
Just work with POSTMAN :
and update the company.js like this
exports.createCompany = (req, res, next) => {
console.log( req.body);
// req.body.company = JSON.parse(req.body.company);
const company = new Company({
coid:req.body.coid,
coname: req.body.coname,
service: req.body.service,
address: req.body.address,
state: req.body.state,
zip: req.body.zip,
city: req.body.city,
country: req.body.country,
size: req.body.size,
domain: req.body.domain,
duns: req.body.duns,
tid1: req.body.tid1,
numid1: req.body.numid1,
tid2: req.body.tid2,
numid2: req.body.numid2,
tid3: req.body.tid3,
numid3: req.body.numid3,
bankname: req.body.bankname,
bicswift: req.body.bicswift,
iban: req.body.iban,
datecreat: req.body.datecreat,
bogid: req.body.bogid
});
company.save().then(
() => {
res.status(201).json({
message: 'Post saved successfully!'
});
}
).catch(
(error) => {
res.status(400).json({
error: error
});
}
);
};
I think the problem come from a bad data format. But How to set it correctly ?
The .save function returns a callback and not a promise.
So if you modify your request handler as follows it will work:
const Company = require('../models/company');
const fs = require('fs');
exports.createCompany = (req, res, next) => {
req.body.company = JSON.parse(req.body.company);
const company = new Company({
coid:req.body.company.coid,
coname: req.body.company.coname,
service: req.body.company.service,
address: req.body.company.address,
state: req.body.company.state,
zip: req.body.company.zip,
city: req.body.company.city,
country: req.body.company.country,
size: req.body.company.size,
domain: req.body.company.domain,
duns: req.body.company.duns,
tid1: req.body.company.tid1,
numid1: req.body.company.numid1,
tid2: req.body.company.tid2,
numid2: req.body.company.numid2,
tid3: req.body.company.tid3,
numid3: req.body.company.numid3,
bankname: req.body.company.bankname,
bicswift: req.body.company.bicswift,
iban: req.body.company.iban,
datecreat: req.body.company.datecreat,
bogid: req.body.company.bogid
});
company.save(function (err, newCompany) {
if (err) {
return res.status(400).json({ error: error });
}
return res.status(201).json(newCompany);
});
};
So I Found the SOLUTION ^^ So proud ** ((^o^)/)**
After the update in the first post, I see that the problem is Content-type Error.
So in ** company service** (Angular) I add this to Force JSON Type !
import { HttpClient, HttpClientModule,** HttpHeaders** } from '#angular/common/http';
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
})
};
CreateCoData(company: Company) {
return new Promise((resolve, reject) => {
this.http.post('http://localhost:3000/api/company', company, **this.httpOptions**).subscribe(
(response) => {
resolve(response);
},
(error) => {
reject(error);
}
);
});
}

why internal server error ?

POST http://localhost:3000/basicUser/saveUser 500 (Internal Server Error)
Error: Request failed with status code 500
at createError
i get a object with date here , obj : [name: "sourav", phone: "1111111"]
action.js
import { browserHistory } from 'react-router';
import axios from 'axios';
export function saveBasicUser(obj) {
console.log("console log from actions...........")
console.log(obj)
return (dispatch) => {
return axios.post('/basicUser/saveUser', {
headers: { 'Content-Type': 'application/json' },
obj: obj
}).then(function (res) {
console.log(" response from action")
console.log( res)
}).catch(function (err) {
console.log(" err")
console.log( err)
})
}
}
server.js
var basicController = require('./controllers/basicController');
app.post('/basicUser/saveUser', basicController.savebasicUser);
controller file
var dotenv = require('dotenv');
dotenv.load();
var mongoose = require('mongoose');
var BasicUser = require('../models/basicUser');
const fetch = require('node-fetch');
exports.savebasicUser = function(req, res) {
console.log("-------------req from controller-----")
console.log(req)
}
According to this,
you can try to print the error that you are receiving by using console.log(error.response.data); in your action.js

Resources