So I got an express route
router.post('/:make&:model&:year', function (req, res) {
const newCar = {
make: req.params.make,
model: req.params.model,
year: req.params.year
}
Car.create(newCar);
res.send(newCar);});
So this works on above using postman
http://localhost:8000/buildings/Audi&A4&2018
I wanna know how would the Axios post go in react functional component. Here's what I have but it doesn't hit the route in express.
const [carFetch, setFetch] = useState('');
const postAxios = async () => {
const payload = { make: 'Audi', model: 'A4', year: 2018 };
const { data } = await axios.post('http://localhost:1337/cars/', payload);
setFetchedData(data);
};
But it doesn't work.
~SRJ
CodePudding user response:
Not sure what we're trying to achieve here but here's a solution: Given your parameters in express are designed the way they are, we need to pass arguments as a string object:
const [carFetch, setFetch] = useState('');
const postAxios = async () => {
const payload = `Audit&A4&2018`;
const url = `http://localhost:1337/cars/${payload}`;
const { data } = await axios.post(url);
setFetchedData(data);
};
This should hit the express URL, and should make the post call.
CodePudding user response:
If the request doesn't hit express route handler there should be a problem with url matching.
And if you send the request the way your react code sample shows you should look for data in req.body object at the rout handler.