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);
}
);
});
}
Related
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
i have added my detect face Clarifai API key to the backend so that the autorization code(API) won't show up in the console, and now It stopped detecting all the faces
I'm getting the below error message in the console
TypeError: data.outputs is undefined
calculateFaceLocation App.js:49
onButtonSubmit App.js:95
promise callback*./src/App.js/</App/this.onButtonSubmit App.js:72
React 23
js index.js:8
js main.chunk.js:2298
Webpack 7
see backend below
const express = require('express');
const bodyParser = require('body-parser');
const bcrypt = require('bcrypt-nodejs');
const cors = require('cors');
const knex = require('knex');
const register = require('./controllers/register');
const signin = require('./controllers/signin');
const profile = require('./controllers/profile');
const image = require('./controllers/image');
const db = knex({
client: 'pg',
connection: {
host : '127.0.0.1',
user : 'postgres',
port: 5432,
password : 'Moshe6700',
database : 'smart-brain'
}
});
const app = express();
app.use(bodyParser.json())
app.use(cors())
app.get('/', (req, res) => {res.send(database.users) })
app.post('/signin', (req, res) => {signin.handleSignin(req, res, db, bcrypt)})
app.post('/register', (req, res) => {register.handleRegister(req, res, db, bcrypt)})
app.get('/profile/:id', (req, res) => {profile.handleProfile(req, res, db)})
app.put('/image', (req, res) => {image.handleImage(req, res, db)})
app.post('/imageurl', (req, res) => {image.handleApiCall(req, res)})
app.listen(3001, () => {
console.log('app is running on port 3001')
})
image.js in the backend
const Clarifai = require('clarifai');
const app = new Clarifai.App({
apiKey: '489560069986431e89aa152fe709ba94'
});
const handleApiCall = (req, res) => {
app.models
.predict(Clarifai.FACE_DETECT_MODEL, req.body.input)
.then(data => {
res.json(data);
})
.catch(err => res.status(400).json('unable to work with API'))
}
const handleImage = (req, res, db) => {
const { id } = req.body;
db('users').where('id', '=', id)
.increment('entries', 1)
.returning('entries')
.then(entries => {
res.json(entries[0].entries)
})
.catch(err => res.status(400).json('unable to get entries'))
}
module.exports = {
handleImage:handleImage,
handleApiCall:handleApiCall
}
frontend code
import React, {Component} from 'react';
import Navigation from './components/Navigation/Navigation';
import Logo from './components/Logo/Logo';
import ImageLinkForm from './components/ImageLinkForm/ImageLinkForm';
import FaceRecognition from './components/FaceRecognition/FaceRecognition';
import Rank from './components/Rank/Rank';
import Signin from './components/Signin/Signin';
import Register from './components/Register/Register';
import './App.css';
const intialState = {
input: '',
imageUrl: '',
box: {},
route: 'signin',
isSignedIn: false,
user: {
id: '',
name: '',
email: '',
entries: 0,
joined: ''
}
}
class App extends Component {
constructor() {
super();
this.state = intialState
}
loadUser = (data) => {
this.setState({user: {
id: data.id,
name: data.name,
email: data.email,
entries: data.entries,
joined: data.joined
}})
}
calculateFaceLocation =(data) => {
console.log(data)
const clarifaiFace = data.outputs[0].data.regions[0].region_info.bounding_box;
const image = document.getElementById('inputimage');
const width = Number(image.width);
const height = Number(image.height);
return {
leftCol: clarifaiFace.left_col * width,
topRow: clarifaiFace.top_row * height,
rightCol: width - clarifaiFace.right_col * width,
bottomRow: height - clarifaiFace.bottom_row * height,
}
}
displayFaceBox = (box) => {
console.log(box)
this.setState({box: box});
}
onInputChange = (event) => {
this.setState({input: event.target.value})
}
onButtonSubmit = () => {
this.setState({imageUrl: this.state.input})
fetch('http://localhost:3001/imageurl', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
input: this.state.input
})
})
.then(response => response.json())
.then( response => {
if (response) {
fetch('http://localhost:3001/image', {
method: 'put',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
id: this.state.user.id
})
})
.then(response => response.json())
.then(count => {
this.setState(Object.assign(this.state.user, { entries: count}))
})
.catch(console.log)
}
this.displayFaceBox(this.calculateFaceLocation(response))
})
.catch(err => console.log(err));
}
onRouteChange = (route) => {
if (route === 'signout') {
this.setState(intialState)
} else if (route === 'home') {
this.setState({isSignedIn: true})
}
this.setState({route:route});
}
render() {
return (
<div className="App">
<Navigation isSignedIn={this.state.isSignedIn} onRouteChange={this.onRouteChange} />
{ this.state.route === 'home'
? <div>
<Logo />
<Rank
name={this.state.user.name}
entries={this.state.user.entries}/>
<ImageLinkForm
onInputChange={this.onInputChange}
onButtonSubmit={this.onButtonSubmit} />
<FaceRecognition box={this.state.box} imageUrl={this.state.imageUrl}/>
</div>
:(
this.state.route === 'signin'
?<Signin loadUser={this.loadUser} onRouteChange={this.onRouteChange} />
:<Register loadUser={this.loadUser} onRouteChange={this.onRouteChange} />
)
}
</div>
);
}
}
export default App;
Any ideas why this is happening?
Your stackstace is quite clear
TypeError: data.outputs is undefined
calculateFaceLocation App.js:49
data.outputs that is provided to calculateFaceLocation function seems to be undefined
From what I see you only call this function in your onButtonSubmit which mean that
fetch('http://localhost:3001/imageurl', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
input: this.state.input
})
})
.then(response => response.json())
.then( response => {
// response here is probably not as you expect
...
this.displayFaceBox(this.calculateFaceLocation(response))
});
=> Probably that the data that is sent back from your back endpoint is malformatted
I'm stuck with that request already. I'm trying to send FormData to NodeJS server but all I got in backend when I console.log the req.body is empty object. I checked the FormData keys/values and it's all good.
Here is my POST request in frontend:
const createProduct = (e: any) => {
e.preventDefault();
const data = new FormData()
data.append("name", name)
data.append("description", description)
data.append("price", price)
for (const colorAndImage of colorsAndImages) {
data.append('images', colorAndImage.images[1]);
data.append('colors', colorAndImage.colors);
}
data.append("type", type)
for (var pair of data.entries()) {
console.log(pair[0]+ ', ' + pair[1]); // the keys/values are correct
}
fetch('http://localhost:4000/products/create', {
method: 'POST',
body: data
})
.then(response => {
if (response.status === 201) {
setName('')
setDescription('')
setPrice('')
setType('')
} else if (response.status === 500) {
console.log('error');
}
})
.catch(error => console.log(error));
}
And my controller in backend:
productController.post('/create', async (req: Request, res: Response) => {
console.log(req.body)
try {
const data = {
name: req.body.name,
description: req.body.description,
price: req.body.price,
colors: req.body.colors,
images: req.body.images,
type: req.body.type,
likes: req.body.likes
}
let product = await create(data)
res.status(201).json(product)
} catch (error) {
console.log(error);
//res.status(500).json({error: error})
}
})
Even that I obviously send some data, the req.body is an empty object and I got that error:
Error: Product validation failed: name: Path 'name' is required.,
description: Path 'description' is required., price: Path 'price' is
required., type: Path 'type' is required.
at ValidationError.inspect
UPDATE
My express config:
import express, { Application } from 'express';
import cookieParser from 'cookie-parser';
import cors from 'cors';
import auth from '../middlewares/auth';
const corsConfig: cors.CorsOptions = {
credentials: true,
origin: ['http://localhost:3000', 'http://localhost:2000']
}
export default function (app: Application) {
app.use(cors(corsConfig))
app.use(cookieParser());
app.use(express.urlencoded({ extended: false }));
app.use(express.json())
app.use(auth())
}
And root server:
import express, { Application } from "express";
import routes from './routes'
import config from './config/config'
import mongooseConfig from './config/mongoose'
import expressConfig from './config/express'
const app: Application = express()
expressConfig(app);
mongooseConfig();
app.use(express.json())
app.use(routes)
app.listen(config.PORT, () => console.log(`Server is listening on port ${config.PORT}`))
Routes file:
import { Router } from "express";
import authController from "./controllers/authController";
import productController from "./controllers/productController";
const routes = Router()
routes.use('/auth', authController)
routes.use('/products', productController)
export default routes;
Maybe you can just submit it as JSON instead of Form data, this works always :smile:
const createProduct = (e: any) => {
e.preventDefault();
const data = {
"name": name,
"description": description,
"price": price,
"colorsAndImages": colorsAndImages,
"type": type,
};
// Please check mappings as I just transferred what you had :smile:
fetch('http://localhost:4000/products/create', {
method: 'POST',
body: JSON.stringify(data),
})
.then(response => {
if (response.status === 201) {
setName('')
setDescription('')
setPrice('')
setType('')
} else if (response.status === 500) {
console.log('error');
}
})
.catch(error => console.log(error));
}
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.
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.