React pass params with Axios post - node.js

I want to pass a params to server using Axios.post but it didn't work with 404 error any ideas??
code:
function Movie() {
const { index } = useParams(); // get index from path /movie/:index
const [movie, setMovie] = useState([]);
useEffect(() => {
Axios.post("http://localhost:3001/movie", {
params: { id: index },
})
.then((response) => {
setMovie(response.data);
})
.catch((err) => {
console.log(err);
});
}, []);
return (
<body>
abc
{index}
{movie.id}
</body>
);
}
Server:
app.post('/movie', async (req, res)=>{
let id= req.params.id;
let movie=[];
movie.push(id);
res.send(movie);
});

A 404 Error means that the path /movie cannot be found on the API. Perhaps ensure that the route on your server is named correctly.

Related

ERR_ABORTED 431 (Request Header Fields Too Large)

Have started using a proxy for my react app/express server. Currently I am trying to run a simple fetch operation but getting this response:
GET http://localhost:3000/api/recipes net::ERR_ABORTED 431 (Request Header Fields Too Large)
I have tried adjusting the allowable size of headers in my package.json I have cleared cache, the header I am sending seems reasonably small. So really scratching my head on this one.
Here is my code:
RecipeList.jsx
export default function RecipeList() {
const [recipeList, setRecipeList] = useState([])
const retrieveAllRecipes = function () {
fetch('/api/recipes', {
method: 'GET',
})
.then((response) => {
console.log(response)
})
.catch((err) => {
console.log('Error Reading data ' + err)
})
}
routes.js
const express = require('express')
const db = require('./db')
const router = express.Router()
router.get('/api/recipes', (req, res) => {
db.readRecipes()
.then((result) => {
console.log(result)
})
.catch((err) => {
logError(err)
})
})
function logError(err) {
console.error('Uh oh!', err.message)
}
module.exports = {}
db.js
const config = require('./knexfile').development
const connection = require('knex')(config)
function readRecipes(db = connection) {
return db('recipes').select()
}
module.exports = {
readRecipes,
}
I am using node v16x and have altered my package.json for my proxy:
"proxy": "http://localhost:3001",

xhr.js:210 DELETE http://localhost:3000/posts/62575cb61cb27c6417732193 403 (Forbidden) / cannot delete document

I am using axios for the request of my own api, everything works correctly except the DELETE request, I looked for information about the error but I have not found the solution. when I send the request to the server I get this error: "xhr.js:210 DELETE http://localhost:3000/posts/62575cb61cb27c6417732193 403 (Forbidden)".
I put this line of code in Package.Json to avoid problems with CORS:
"proxy": "http://localhost:8080/api"
This would be my api, for the operation I pass the post id by url and the user id:
(I tried it in postman and it works without any problem)
router.delete("/:id", async (req, res) => {
try {
const post = await Post.findById(req.params.id);
if (post.userId === req.body.userId) {
await post.deleteOne();
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);
}
});
and this is where I consume my api:
const Post = ({ date, _id,userId, description }) => {
const handleDelete = async () => {
try {
await axios.delete('posts/' + _id, { userId: currentUser._id })
} catch (error) {
console.log(error)
}
}
return(
<div onClick={handleDelete }>
//component content
</div>
)
}
export default Post
I solved it, sending a data object to my api (inside that object I put the user id):
const handleDelete = async () => {
try {
await axios.delete('/posts/' + _id, {
data: {
userId: currentUser._id
}
}
)
} catch (error) {
console.log(error)
}
}

How to send React to Express server get Request passing id

Hello I am learning on MERN Stack dev, so I am trying to implement a get request where by I send in and ID and then try searching through the collection by the id the return the entry back to the client so I have been trying to implement this but I do not know where I am going wrong because I get a 404 response
Code below is the client side where I try to send through the get request
const ProductDetails = (props) => {
const product_id = window.location.href.split("/")[4];
console.log(product_id);
const getProduct = () => {
const url = `http://127.0.0.1:5000/single-women-clothes/id?=${product_id}`;
Axios.get(url)
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.log(error);
});
};
getProduct();
return (
<div>
<h1>Details</h1>
</div>
);
};
router.get("/single-womens-clothes/:id", (request, response) => {
console.log(request.params);
MongoClient.connect(
mongoURI,
{ useNewUrlParser: true, useUnifiedTopology: true },
(error, client) => {
client
.db("OnlineStore")
.collection("WomensClothes")
.find(request.params.id)
.toArray()
.then((data) => {
response.status(200).json(data);
})
.then((response) => {
console.log("Single Female Product Fetch Successful");
})
.catch((error) => {
console.log(error);
});
}
);
});
Can I please get help on how I can pass the ID to the server then search through collection through this given ID
Anytime you have a 404 error, the issue is usually coming from putting the wrong url.
In your front-end:
single-women-clothes/id?=${product_id}
Backend
/single-womens-clothes/:id
You are missing an "s" in the front-end url in "womens"
To answer your second question:
You shouldn't do id?= just simply leave it as
single-women-clothes/${product_id}

Undefined object when sending a JSON object from Express server into React?

I am new to React and Express. I had created client side on port 8080 with localhost:8080/site3 route:
import React, { Component } from 'react';
export default class Site3 extends Component {
componentDidMount() {
console.log('FETCHING');
fetch('http://localhost:3000/site3', {
method: "GET"
})
.then(res => {
res.json();
})
.then(result => {
console.log(result);
console.log('Finished fetching');
});
}
render() {
return content;
}
}
and server side on port 3000:
const express = require("express");
require("dotenv").config();
const app = express();
const data = [
{ id: "tt0110357", name: "The Lion King", genre: "animation" },
{ id: "tt0068646", name: "The Godfather", genre: "crime" },
{ id: "tt0468569", name: "The Dark Knight", genre: "action" }
];
app.get("/site3", (req, res) => {
console.log("RESPONDING");
res.send(data);
});
// Port 3000
app.listen(process.env.PORT, () =>
console.log(`Service 2 listening on port ${process.env.PORT}!`)
);
After starting both React and Express server, I went to the localhost:8080/site3.
The Express server had get the request from the client, printed RESPONDING and sent a JSON data back to React.
But the React cannot get the JSON data and return to undefined object.
How do I solve this?
return statement is missing in the res.json() call.
componentDidMount() {
console.log('FETCHING');
fetch('http://localhost:3000/site3', {
method: "GET"
})
.then(res => {
return res.json();
})
.then(result => {
console.log(result);
console.log('Finished fetching');
});
}
You can leave the curly brackets from the first .then() like the following:
componentDidMount() {
console.log('FETCHING');
fetch('http://localhost:3000/site3', {
method: "GET"
})
.then(res => res.json())
.then(result => {
console.log(result);
console.log('Finished fetching');
});
}

POST request with Axios not sending data to my server

Here is my React code for the form submission:
const handleSubmit = (e) => {
e.preventDefault();
console.log('item:', item);
Axios.post('http://<MY_SERVER>/item/add', {name:item})
.then(response => console.log(response))
.catch(err => console.log(err));
};
and this is the code in my Node API:
// Add a new Item
app.post('/item/add', (req, res) => {
const newItem = new Item({
name: req.body.name
});
newItem.save()
.then(item => {
res.json({msg: 'success'});
})
.catch(err => console.log(err));
});
When I run the handleSubmit nothing happens. I only get the console.logs... Also, here is the error from my server
'ValidationError: item validation failed: name: Path' `name` is required
So it is clear that the data sent over to the api is never received. I've tried changing it up in many ways I have came across online but no luck.
I have attached both ways to post data i.e. Form URL Encoded and JSON. For sending Form Url Encoded data we need an additional Library querystring.
You can install it using npm install query-string
Here is the code for both the requests. You don't need query-string if you are using content type application/json.
Here you go
var axios = require('axios');
const qs = require('querystring');
function sendFormUrlEncodedData() {
const headers = {
'Content-Type': 'application/x-www-form-urlencoded'
};
const payload = {
name: 'morpheus',
job: 'leader'
};
//Send data with form url using querystring node package for it.
axios
.post('https://reqres.in/api/users', qs.stringify(payload), {
headers: headers
})
.then(res => {
console.log(res.data);
})
.catch(err => {
console.log(err);
});
}
function sendJSONData() {
const headers = {
'Content-Type': 'application/json'
};
const payload = {
name: 'morpheus',
job: 'leader'
};
//Send data with JSON, so stringifying it.
axios
.post('https://reqres.in/api/users', JSON.stringify(payload), {
headers: headers
})
.then(res => {
console.log(res.data);
})
.catch(err => {
console.log(err);
});
}
sendFormUrlEncodedData();
sendJSONData();
First of all check whether your backend code is working or not by using postman. I think you are getting validation error because of the error of your backend code. And also check whether that you are implemented the name attribute correctly with its data type.
After that update, the react code as below.
import axios from 'axios';
constructor() {
this.item = {
name: ''
}
}
handleSubmit(event) {
console.log('item:', this.item.name);
event.preventDefault();
axios.post('http://<MY_SERVER>/item/add', this.item)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
}

Resources