When i try to call the api data from axios i get 404 error - node.js

code for HomeScreen.js to fetch the data:
Setting proxy in package.json
"proxy": "http://127.0.0.1:5000"
I am trying to get the data from the local server as shown in the image below
Error 404 that I get
Image of data to fetch
import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import data from '../data';
import axios from 'axios';
function HomeScreen(props) {
const [products, setProduct] = useState([]);
useEffect(() => {
const fetchData = async () => {
const {data} = await axios.get("/api/products");
setProduct(data);
}
fetchData();
return() => {
};
}, [])
return <ul className="products">
{
products.map(product =>
<li key={product._id}>
<div className="product">
<Link to={'/product/' + product._id}><img className="product-image" src="/images/d1.jpg" alt="Product" />
</Link>
<div className="product-name"><Link to={'/product/' + product._id}> {product.name}</Link></div>
<div className="product-brand">{product.brand}</div>
<div className="product-price">{product.price}</div>
<div className="product-rating">{product.rating} Stars {product.numReviews}</div>
</div>
</li>
)
}
</ul>
}
export default HomeScreen;

You're trying to fetch data with relative path /api/products and if you see your error, browser is trying to fetch http://localhost:3000/api/products.
Change your fetch to this:
axios.get("http://localhost:5000/api/products");
or you should run your react app on port 5000

Related

Fetch request unable to get backend data due to Uncaught AxiosError - next.js and express.js

I'm trying to fetch some backend data on my Express.js backend which looks like this:
const express = require('express')
const app = express()
app.get("/api", (req, res) => {
res.json({"data": ["data1", "data2", "data3"]})
})
app.listen(5000, () => { console.log("Server started on port 5000, hi") })
Every time the specific page loads I want it to fetch the {"data": ["data1", "data2", "data3"]} from the backend, I added a button that makes the same request for testing as well. Whenever I click the button and whenever the page loads I get this error:
I don't really understand why I'm getting this error, here is my next.js code:
import React, { Component, useEffect, useState } from 'react';
import axios from 'axios';
export default function Product() {
const [backendData, setBackendData] = useState([{}])
useEffect(() => {
axios.get('/api').then(
response => response.json()
).then(
data => {
setBackendData(data)
}
)
console.log("ran")
}, [])
const test = () => {
axios.get('/api').then(
response => response.json()
).then(
data => {
setBackendData(data)
}
)
console.log("test clicked")
}
return (
<div style={styles.container}>
<div style={styles.speechTitle}>Talk to us, tell us about your day...</div>
<div style={styles.speechBox}>
Test
</div>
<button onClick={console.log("start")}>
Start
</button>
<button onClick={console.log("stop")}>Stop</button>
<button onClick={console.log("reset")}>Reset</button>
{(typeof backendData.data === 'undefined') ? (
<p>Loading...</p>
) : (
backendData.data.map((data, i) => (
<p key={i}>{data}</p>
))
)}
<button onClick={() => test()}>asdasd</button>
</div>
);
}
I'm running this component called Product you see above in this file called product.js which is in my pages folder:
import React from 'react';
import { ThemeProvider } from 'theme-ui';
import { StickyProvider } from 'contexts/app/app.provider';
import theme from 'theme';
import SEO from 'components/seo';
import Layout from 'components/layout';
import Product from 'components/product-input'
export default function ProductPage() {
return (
<ThemeProvider theme={theme}>
<StickyProvider>
<Layout>
<SEO title="Talkhappi" />
<Product/>
</Layout>
</StickyProvider>
</ThemeProvider>
);
}
I am also getting a network error when I open up the network tab in developer tools:
I'm unsure how to fix this problem and retrieve the data I want to retrieve from my backend running at port 5000.
You seem to have to call your apis at port 5000 instead of 3000 you did.
const baseURL = 'http://localhost:5000';
const test = () => {
axios.get(baseURL + '/api').then(
response => response.json()
).then(
data => {
setBackendData(data)
}
)
console.log("test clicked")
}

NEXT.js Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource

Hi guys I've created fullstack app with NEXT.js, TypeScript, NODE.js and MongoDB. Generally this is decode\encode app with all functionality on Backend side. My backend side is already deployed on heroku. Front-end I still have on a localhost till I solve this problem. When I fetch all of my data from Backend, first I see error mesage, then data from Backend.
Here below error msg:
And here below my code:
import { ListProps } from "./List.props";
import styles from "./List.module.css";
import { P } from '../'
import React, { useEffect, useState } from "react";
import axios from "axios";
export const List = ({ children, className, ...props }: ListProps): JSX.Element => {
const [blogs, setBlogs] = useState<any[]>([]);
useEffect(() => {
const fetchData = async () => {
await fetch(`https://node-test-mongo.herokuapp.com/api/blog`)
.then((response) => {
return response.json();
})
.then((data) => {
setBlogs(data.blogs)
})
};
fetchData();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [blogs]);
return (
<div
className={styles.ul}
{...props}
>
{blogs && blogs.map((blog, index) => (
<ul key={blog._id}>
<li className={styles.li}>
<P className={styles.title} size='l'>{blog.title}</P>
<P size='l'>description={blog.text} </P>
</li>
</ul>
))}
</div>
)
};
I suppose, that there could be something wrong with my data fetching, but I'm not sure.
Thank you in advance!:)

useState data not working with .map function

I have this app that fetches the blog posts from an API. The API response with blog posts and I'm getting those blog posts to GetBlogState state. When I'm looping through GetBlogState using the .map I am getting the following error.
The following is the code that I'm currently working with.
import React, { useState, useEffect } from 'react';
import Head from 'next/head'
import axios from 'axios'
import HeaderComponent from '../components/HeaderComponent';
export default function Blog(){
const [GetBlogState, SetBlogState] = useState([]);
useEffect(() => {
axios.get('http://localhost:4000/blog').then(res => {
SetBlogState(res)
}).catch(errr => {
console.log(err)
})
}, []);
return (
<div className="MyApp">
{ GetBlogState.map(item => (
<div className="h-68">
<img className="w-full" alt="post" src='post.jpg' />
<div className="mt-3 mb-2 text-xs">May 10, 2018</div>
<h2 className="font-bold mb-5 text-xl">{ item.Title } </h2>
<p>{item.content}</p>
</div>
))}
</div>
)
}
I think you should check the output what you are getting in res from axios.
you are setting response object in state which is wrong.
You should do
useEffect(() => {
axios.get('http://localhost:4000/blog').then(res => {
//// console.log(res) Check whats returning in res \\\
SetBlogState(res.data)
}).catch(errr => {
console.log(err)
})
}, []);
Axios' response schema put server response in data. Hence set state like SetBlogState(res.data)

how to solve this no-unused-vars error in NodeJS?

I am creating a todo app using MERN stack.I am new to MERN stack technology and I kindly neeed your help solving this error.I have provided the code for my app.js file and todo.js file.I can't clearly find the solution of this error anywhere on the internet.
I am getting this error while runnng the node js app using npm start command.
Compiled with warnings.
src\App.js
Line 4:8: 'Todo' is defined but never used no-unused-vars
Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.
App.js
import React from 'react';
import logo from './logo.svg';
import './App.css';
import Todo from './components/Todo.js';
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;
Todo.js
import React, { Component } from 'react'
import axios from 'axios';
// eslint-disable-next-line
export class Todo extends Component {
constructor(props) {
super(props)
this.state = {
todos : [],
item : ""
}
}
changeHandler = (event) => {
this.setState({item: event.target.value})
}
clickHandler = (event) => {
event.preventDefault()
console.log(this.state.item)
axios({
method: 'post',
url: 'http://localhost:3000/',
data: {
todo: this.state.item,
}
});
this.setState({item:''})
}
componentDidMount() {
axios.get('http://localhost:3000/').then((response) => {
console.log(response.data.data)
let data = [];
console.log(response.data.data.length)
for(var i =0; i < response.data.data.length; i++){
data.push(response.data.data[i].todo)
}
this.setState({todos: data})
});
}
componentDidUpdate() {
axios.get('http://localhost:3000/').then((response) => {
console.log(response.data.data)
let data = [];
console.log(response.data.data.length)
for(var i =0; i < response.data.data.length; i++){
data.push(response.data.data[i].todo)
}
this.setState({todos: data})
});
}
render() {
return (
<div>
<input type="text" onChange={this.changeHandler}/>
<button type="submit" onClick={this.clickHandler}>add</button>
<div>
<ul>{this.state.todos.map((todo, index) => <li key={index}>{todo}</li>)}</ul>
</div>
</div>
)
}
}
export default Todo
That warning you are getting because even though you are importing Todo file in your App.js file but you aren't using it anywhere.Either try using it in App.js or remove the import(in case you don't need it).That should fix the warning.
Or add // eslint-disable-next-line just before the import Todo.. statement in App.js

Error Getting Data from API using FetchData

i am using a react hook : useEffect for getting data from an API and i'm also using .map for rendering an array of product.
after run the npm , there is an error :
xhr.js:178 GET http://localhost:3000/api/products 404 (Not Found)
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios'
function HomeScreen (props) {
// menggunakan hooks
const [products, setProduct] = useState([]);
// fetchDate from server // sama dengan component did mount
useEffect( () =>{
const fetchData = async () => {
const { data } = await axios.get("/api/products");
setProduct(data)
}
return () => {
fetchData();
}
}, [])
return(
<div>
<ul className="products">
{
products.map( product =>
<li key={product.id}>
<div className="product" >
<Link to = {`/product/${ product.id }`}>
<img className='product-image' src={ product.image } alt={product.name} />
</Link>
<div className="product-name">
<Link to = {`/product/${ product.id }`}>{ product.name }</Link>
</div>
<div className="product-cat">{ product.brand }</div>
<div className="product-price"><b>IDR</b> { product.price }</div>
<div className="product-rating">{ product.rating } Stars ( { product.reviews } Reviews )</div>
</div>
</li>
)
}
</ul>
</div>
)
}
export default HomeScreen
and there is code from server.js
const express = require('express');
const data = require('./database/data')
const app = express();
app.get('/api/products', ( req, res) => {
res.send(data.Products)
})
const PORT = process.env.PORT || 5001
app.listen(PORT, () => {
console.log(`Server is Running on http://localhost:${PORT}`)
} )
i really hope this problem solving of this code, thank you
You are calling your API on localhost:3000, but your API should be running on localhost:5001
const { data } = await axios.get("http://localhost:5001/api/products");
You want to initialize your state with brackets "[]" instead of "{}"
const [products, setProducts] = useState([])
Also, you might want to code defensively by adding a turnery operation to check to see if products is 'truthy' if it's not, then the user will see some kind of error message i.e. the part after the ":".
{products ? products.map( product => {}) : <div>handle error</div> }
finally i've got this solve
i miss the set proxy server of the front end site, thanks !
Just you need to do is install cors by using below command:
npm install core
//Then use it in server file like this:
var cors = require('cors')
app.use(cors())

Resources