TypeError: data.outputs is undefined - node.js

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

Related

MongoDB update user

I'm trying to update user, but it gives me this error:
I can't find any solution of it. Tried to use different UserSchema methods, like findOneAndUpdate, updateOne, but nothing helps..
This is my mainController:
updateUser: async (req, res) => {
try {
const updatedUser = await UserSchema.updateOne({ secret: req.params.secret }, { $set: req.body });
res.status(200).json(updatedUser);
} catch (error) {
res.status(400).json({ message: error.message });
}
},
This is my router:
mainRouter.post('/update/:secret', updateUser)
This is where I'm posting in front end:
import React, { useState, useEffect } from 'react';
import { Link, useParams, useNavigate } from 'react-router-dom';
import Toolbar from '../components/Toolbar';
import { get, post } from '../helper/helper';
export default function TestPage() {
const [current, setCurrent] = useState('')
const [index, setIndex] = useState(0);
const [allUsers, getAllUsers] = useState([])
const secret = window.localStorage.getItem('secret')
const nav = useNavigate()
useEffect(() => {
async function currentUser() {
const resp = get(`user/${secret}`)
setCurrent(resp)
}
currentUser()
}, [])
useEffect(() => {
async function fetchUsers() {
const resp = await get('api')
getAllUsers(resp)
}
fetchUsers()
}, [])
allUsers.filter(user => user.secret !== secret)
console.log(index)
const currentUser = allUsers[index];
async function postLiked() {
const likedObj = {
liked: [currentUser]
}
const likesObj = {
likes: [current]
}
await post(`update/${current.secret}`, likedObj)
await post(`update/${currentUser.secret}`, likesObj)
}
async function postDislike() {
const dislikeObj = {
disliked: [currentUser]
}
await post(`update/${current.secret}`, dislikeObj)
}
return (
<div className='home__page'>
<Toolbar />
<div className="home__users">
<div className='single__user'>
<img src={currentUser && currentUser.image[0]} alt="" />
<h3>{currentUser && `${currentUser.firstName} ${currentUser.lastName}`}</h3>
<h4>{currentUser && currentUser.gender}</h4>
<button onClick={() => { setIndex(index + 1); postDislike(); nav(`/${currentUser.secret}`) }}>Dislike</button>
<button onClick={() => { setIndex(index + 1); postLiked(); nav(`/${currentUser.secret}`) }}>Like</button>
</div>
</div>
<footer className='footer'>
<p>All rights reserved by Cartoon Match organization. To read more about our policy <Link to='/policy'>click here</Link>. </p>
</footer>
</div>
)
}
helper.js:
export const get = async (url) => {
const options = {
method: 'GET',
headers: {
'Content-type': 'application/json',
},
};
const response = await fetch(`http://localhost:4000/${url}`, options);
if (response.ok) {
const dataFromGetRequest = await response.json();
return dataFromGetRequest;
}
};
export const post = async (body, url) => {
const options = {
method: 'POST',
headers: {
'Content-type': 'application/json',
},
body: JSON.stringify(body),
};
const response = await fetch(`http://localhost:4000/${url}`, options);
if (response.ok) {
const dataFromPostRequest = await response.json();
return dataFromPostRequest;
}
};
export const put = async (body, url) => {
const options = {
method: 'PUT',
headers: {
'Content-type': 'application/json',
},
body: JSON.stringify(body),
};
const response = await fetch(`http://localhost:4000/${url}`, options);
if (response.ok) {
const dataFromPostRequest = await response.json();
return dataFromPostRequest;
}
};
If react and node.js run on different port, Browser refuse to connect.
Add this line after const app = express();
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "POST,OPTIONS, GET, PUT, PATCH, DELETE");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization,token-type");
next();
});

When clicking on detect a face even witout entering url the numbers are still moving up

i am currenty using the Clarifai API to detect faces, i also created that whenever i detect a face the numbers are moving up
see below imageurl image
however, when i click on detect, even without entering any url, the number still moves up, how can i prevent it from moving up when nothing is entered,
see my code below
FRONTEND code App.js
import React, { Component } from 'react';
import Particles from 'react-particles-js';
import FaceRecognition from './components/FaceRecognition/FaceRecognition';
import Navigation from './components/Navigation/Navigation';
import Signin from './components/Signin/Signin';
import Register from './components/Register/Register';
import Logo from './components/Logo/Logo';
import ImageLinkForm from './components/ImageLinkForm/ImageLinkForm';
import Rank from './components/Rank/Rank';
import './App.css';
const particlesOptions = {
particles: {
number: {
value: 30,
density: {
enable: true,
value_area: 800
}
}
}
}
const initialState = {
input: '',
imageUrl: '',
box: {},
route: 'signin',
isSignedIn: false,
user: {
id: '',
name: '',
email: '',
entries: 0,
joined: ''
}
}
class App extends Component {
constructor() {
super();
this.state = initialState;
}
loadUser = (data) => {
this.setState({user: {
id: data.id,
name: data.name,
email: data.email,
entries: data.entries,
joined: data.joined
}})
}
calculateFaceLocation = (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) => {
this.setState({box: box});
}
onInputChange = (event) => {
this.setState({input: event.target.value});
}
onButtonSubmit = () => {
this.setState({imageUrl: this.state.input});
fetch('https://ancient-sea-46547.herokuapp.com/imageurl', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
input: this.state.input
})
})
.then(response => response.json())
.then(response => {
if (response) {
fetch('https://ancient-sea-46547.herokuapp.com/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(initialState)
} else if (route === 'home') {
this.setState({isSignedIn: true})
}
this.setState({route: route});
}
render() {
const { isSignedIn, imageUrl, route, box } = this.state;
return (
<div className="App">
<Particles className='particles'
params={particlesOptions}
/>
<Navigation isSignedIn={isSignedIn} onRouteChange={this.onRouteChange} />
{ route === 'home'
? <div>
<Logo />
<Rank
name={this.state.user.name}
entries={this.state.user.entries}
/>
<ImageLinkForm
onInputChange={this.onInputChange}
onButtonSubmit={this.onButtonSubmit}
/>
<FaceRecognition box={box} imageUrl={imageUrl} />
</div>
: (
route === 'signin'
? <Signin loadUser={this.loadUser} onRouteChange={this.onRouteChange}/>
: <Register loadUser={this.loadUser} onRouteChange={this.onRouteChange}/>
)
}
</div>
);
}
}
export default App;
BACKEND code image.js
const Clarifai = require('clarifai');
const app = new Clarifai.App({
apiKey: '378c71a79572483d9d96c7c88cb13a7a'
});
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,
handleApiCall
}
anything i can add to prevent it?
It seems the issue is with how you handle state object, and not with the Clarifai API. For example, instead of directly modifying the state using this.state, try using this.setState(). This way, when a value in the state object changes, the component will re-render, implying that the output will change according to the new values of the detected faces.
i figured the issue,
My frontend logic woudlnt work because I'm just returning a JSON object and not assigning any status code as such. So when i receive a JSON response you cannot say if(response) because in both the cases of success and failure you get a JSON and your if condition will always be true. So instead, i just wrapped the fetch call
with an if condition saying if(this.state.input) so that you handle the case where users cannot click on a button without entering an URL

React/Postgres sql detail: 'Failing row contains (43, ccc, null, 0, 2022-07-01 15:37:11.631)

**I am getting the error when I am connecting the frontend code as well as backend code with the database maybe the problem might be in front end but pls let me know the meaning of the error because I am newbie.I am getting the error on register pls help me and also when I register the website using frontend it shows me error on **localhost/register
enter image description here
const express = require('express');
const { listen } = require('express/lib/application');
const bodyParser=require('body-parser');
const bcrypt=require('bcrypt-nodejs')
const cors = require('cors')
const knex = require('knex');
const { response } = require('express');
const db=knex({
client: 'pg',
connection: {
host : '127.0.0.1',
user : 'postgres',
password : '224898',
database : 'smart-brain'
}
});
const app = express();
app.use(bodyParser.json());
app.use(cors())
const database={
users:[
{
id:'123',
name:'John',
email:'John#gmail.com',
password:'ABC',
entries:0,
joined:new Date()
},
{
id:'124',
name:'ABC',
email:'ABC',
password:'123',
entries:0,
joined:new Date()
}
],
login:[
{
id:'987',
hash:'',
email:'John#gmail.com'
}
]
}
app.get('/' ,(req,res)=>{
res.send(database.users);
})
app.post('/signin',(req,res)=>{
if(req.body.email===database.users[0].email && req.body.password===database.users[0].password){
res.json(database.users[0]);
}else{
res.status(400).json('error login in');
}
})
app.post('/register',(req,res)=>{
const{email,name,password}=req.body;
db('users')
.returning('*')
.insert({
email:email,
name:name,
joined: new Date()
})
.then(user=>{
res.json(user[0]);
})
. catch(err => console.log(err))
})
app.get('/profile/:id',(req,res)=>{
const{id}=req.params;
let found=false;
database.users.forEach(user=>{
if(user.id===id){
found=true;
return res.json(user);
}
})
if(!found){
res.status(400).json('not found');
}
})
app.put('/image',(req,res)=>{
const{id}=req.body;
let found=false;
database.users.forEach(user=>{
if(user.id===id){
found=true;
user.entries++
return res.json(user.entries);
}
})
if(!found){
res.status(400).json('not found');
}
})
// // Load hash from your password DB.
// bcrypt.compare("bacon", hash, function(err, res) {
// // res == true
// });
// bcrypt.compare("veggies", hash, function(err, res) {
// // res = false
// });
app.listen(3000,()=>{
console.log('app is running on port 3000 ');
})
AND ALSO I AM SHARING FRONTEND APP.JS CODE
APP.js code
import './App.css';
import Navigation from './Components/Navigation/Navigation';
import FaceRecognition from './Components/FaceRecognition/FaceRecognition';
import Logo from './Components/Logo/Logo'
import ImageLinkForm from './Components/ImageLinkForm/ImageLinkForm'
import Rank from './Components/Rank/Rank'
import { Component } from 'react';
import Particles from "react-tsparticles";
import { loadFull } from "tsparticles";
import SignIn from './Components/SignIn/SignIn';
import Register from './Components/Register/Register'
const USER_ID = 'aad';
const PAT = 'bd69e06e68f244ed83b9ce09ee560e7c';
const APP_ID = 'aaa';
const MODEL_ID = 'face-detection';
const MODEL_VERSION_ID = '45fb9a671625463fa646c3523a3087d5';
const particlesOption = {
fpsLimit: 120,
particles: {
links: {
color: "#ffffff",
distance: 150,
enable: true,
opacity: 0.5,
width: 1,
},
collisions: {
enable: true,
},
move: {
direction: "none",
enable: true,
outModes: {
default: "bounce",
},
random: true,
speed: 5,
straight: true,
},
},
detectRetina: true,
}
const particlesInit = async (main) => {
await loadFull(main);
};
const initialState = {
input: '',
imageUrl: '',
box: {},
route:'signin',
isSignedIn:false,
user: {
id: '',
name: '',
email: '',
joined: '',
entries: 0
}
};
class App extends Component {
constructor() {
super();
this.state = initialState;
};
loadUser = (data) => {
this.setState({
user: {
id: data.id,
name: data.name,
email: data.email,
entries: data.entries,
joined: data.joined
}
})
}
apiData = () => {
const raw = JSON.stringify({
"user_app_id": {
"user_id": USER_ID,
"app_id": APP_ID
},
"inputs": [
{
"data": {
"image": {
"url": this.state.input
}
}
}
]
});
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Authorization': 'Key ' + PAT
},
body: raw
};
return requestOptions;
}
displayFaceBox = (box) => {
this.setState({ box: box });
}
onInputChange=(event) =>{
this.setState({input: event.target.value});
}
onImageSubmit = () => {
this.setState({ imageUrl: this.state.input });
const requestOptions = this.apiData();
fetch("https://api.clarifai.com/v2/models/" + MODEL_ID + "/versions/" + MODEL_VERSION_ID + "/outputs", requestOptions)
.then(response => response.text())
.then(result => JSON.parse(result))
.then(obj => {
if (obj) {
fetch('http://localhost:3000/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}))
})
}
this.displayFaceBox(this.calculateFaceLocation(obj))
})
.catch(error => console.log('error', error));
}
calculateFaceLocation = (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),
})
}
onRouteChange=(route)=>{
if(route==='signout'){
this.setState({isSignedIn:false})
}else if(route==='home'){
this.setState({isSignedIn:true})
}
this.setState({route:route})
}
render(){
const { imageUrl, box ,isSignedIn,route} = this.state;
return (
<div className="App">
<Particles className='particles'
init={particlesInit}
options={particlesOption}
/>
<Navigation isSignedIn={isSignedIn} onRouteChange={this.onRouteChange} />{ route==='home'?
<div>
<Logo />
<Rank name={this.state.user.name} entries={this.state.user.entries}/>
<ImageLinkForm onInputChange={this.onInputChange}
onImageSubmit={this.onImageSubmit}/>
<FaceRecognition box={box} imageUrl={imageUrl} />
</div> :(
route==='signin'?
<SignIn loadUser={this.loadUser} onRouteChange={this.onRouteChange} />
: <Register loadUser={this.loadUser}onRouteChange={this.onRouteChange}/>
)
}
</div>
);
}
}
export default App;
Do not use images for textual information, copy and paste the text into the question. This would make the following easier.
From error message code:23502. If you go here Error codes you find that corresponds to 23502 not_null_violation. So the value that is being set to NULL is being entered into a column that has NOT NULL set. Your choices are:
a) Make sure the value is not set to NULL.
b) If you can have NULL values in the column drop the NOT NULL constraint.

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.

ReactNative : variable for FormData() being logged as undefined in ReactNative application when i make an http request with a file

i have been trying to make a post request from my react native app on an android emulator but the object that i am sending in the body of the request is being vvalued as undefined,been trying alot to solve this issue but no success. Please help me
here is the code to my form in the app known as "API.js" its named so just for testing the API endpoints
import React, { Component } from "react";
import {
Text,
TextInput,
View,
TouchableHighlight,
StyleSheet,
Button,
FormData
} from "react-native";
import Permissions from "react-native-permissions";
import ImagePicker from "react-native-image-crop-picker";
import axios from "axios";
var styles = StyleSheet.create({});
var msg = "Select Image";
var data;
export default class API extends Component {
constructor(props) {
super(props);
this.state = {
name: "",
price: "",
size: "",
description: "",
image: "",
popularity: ""
};
}
FormDataFunc() {
let form = new FormData();
form.append("name", this.state.name);
form.append("price", this.state.price);
form.append("size", this.state.size);
form.append("description", this.state.description);
form.append("image", this.state.image);
form.append("popularity", this.state.popularity);
return form;
return form;
}
onChange(e) {
this.setState({ [e.target.name]: e.target.value });
}
Submit() {
axios({
method: "post",
url: "http://192.168.0.102:3000/products",
data: this.FormDataFunc,
headers: {
Accept: "application/json",
"Content-Type": "application/x-www-form-urlencoded"
},
body: this.FormDataFunc
})
.then(() => {
console.log("DONE!");
this.props.navigation.navigate("offersScreen");
})
.catch(err => {
console.log(err);
console.log(this.FormDataFunc);
});
}
componentDidMount() {
Permissions.check("photo").then(response => {
// Response is one of: 'authorized', 'denied', 'restricted', or 'undetermined'
console.log(response);
});
}
render() {
const image = () => {
ImagePicker.openPicker({
multiple: false,
includeBase64: true
}).then(images => {
console.log(images);
this.setState({
images: { data: `\`${images.mime}\`;base64,\`${images.data}\`` }
});
console.log(this.state.images);
msg = "Selected";
});
};
return (
<View>
<TextInput placeholder="Name" name="name" />
<TextInput placeholder="Price" name="price" />
<TextInput placeholder="Size" name="size" />
<TextInput placeholder="Description" name="description" />
<TouchableHighlight onPress={image} name="image">
<Text>{msg}</Text>
</TouchableHighlight>
<TextInput placeholder="Popularity" name="popularity" />
<TouchableHighlight title="Submit" onPress={this.Submit}>
<Text>Send</Text>
</TouchableHighlight>
</View>
);
}
}
here is the code to my backend route "product.js" which recieves the request(node.js and express)
const express = require("express");
const router = express.Router();
const bodyParser = require("body-parser");
const path = require("path");
const cloudinary = require("cloudinary");
const mongoose = require("mongoose");
//Product Model
const product = require("../models/product").product;
router.use(bodyParser.json());
//GET route
router.get("/", (req, res) => {
product.find().then(product => res.json(product));
});
// POST route
cloudinary.config({
cloud_name: "cloud222",
api_key: "783935981748815",
api_secret: "uY47vBS1rI2x5jvFtnXQIjMMqU0"
});
router.post("/", (req, res) => {
//MISC//
let imageUrl;
console.log("starting");
//MISC//
//CLOUDINARY UPLOAD
cloudinary.v2.uploader.upload(req.body.image, (error, result) => {
if (error) {
console.log(error);
console.log(`${req.body.image}`);
} else {
imageUrl = result.secure_url;
//MONGO UPLOAD
var productv = {
name: req.body.name,
price: req.body.price,
size: req.body.size,
description: req.body.description,
image: imageUrl,
popularity: req.body.popularity
};
const productvar = new product(productv);
productvar
.save()
.then(product => console.log(product))
.then(product => res.json(product))
.catch(err => console.log(err));
}
});
//END//
});
module.exports = router;
the data is being logged as undefined and therefore the request doesnt get a response
I think the problem is that you have created a FormData and wanted to post it, but the headers you added is "application/json". You should change it:
headers: {
'content-type': 'multipart/form-data',
'Accept':'multipart/form-data',
},
Hope it works for you.
Problem solved
Had to use onChangeText = instead of onChange as onChange does not return a string

Resources