400 BAD REQUEST when POST using Axios in React - javascript

Can any help me with this?
I keep getting a 400 bad request from Axios.
I can pass a GET request and confirm its working fine.
I create http-common.js file with following code:
import axios from 'axios';
export default axios.create({
baseURL: 'https://5fa97367c9b4e90016e6a7ec.mockapi.io/api',
headers: {
'Content-type': 'application/json'
}
});
Then,I create a service that uses axios object above to send HTTP requests.
TodoService.js
import http from '../http-common/http-common';
const getAll=()=>{
return http.get('/todos');
};
const get=id=>{
return http.get(`/todos/${id}`);
};
const create=data=> {
return http.post('/todos',data);
};
const update=(id,data)=>{
return http.put(`/todos/${id}`,data);
};
const remove = id => {
return http.delete(`/todos/${id}`);
};
const removeAll = () => {
return http.delete(`/todos`);
};
const findByTitle = title => {
return http.get(`/todos?title=${title}`);
};
export default {getAll,get,create,update,remove,removeAll,findByTitle};
Then, I use TodoDataService.create(data) ... in AddTodos component.
AddTodos.js
import React, { useState } from 'react';
import TodoDataService from '../services/TodoService';
const AddTodos = () => {
const initialTodoState={
id:null,
title: '',
isDone: false,
user: ''
};
const [todo,setTodo]=useState(initialTodoState);
const [submitted,setSubmitted]=useState(false);
const handleInputChange=event=>{
const {name,value}=event.target;
setTodo({...todo,[name]:value});
};
const saveTodo =()=>{
var data={
title: todo.title,
isDone:todo.isDone,
user: todo.user
};
console.log(data);
TodoDataService.create(data)
.then(response => {
setTodo({
id:response.data.id,
title: response.data.title,
isDone: response.data.isDone,
user: response.data.user
});
setSubmitted(true);
console.log(response.data);
})
.catch(e => {
console.log(e);
});
};
const newTodo=()=>{
setTodo(initialTodoState);
setSubmitted(false);
};
return (
<div className="submit-form">
{submitted ? (
<div> //...
) : (
<div>
<div className="form-group"> //... </div>
<div className="form-group"> //... </div>
<button onClick={saveTodo} className="btn btn-success">
Submit
</button>
</div>
)}
</div>
)
}
export default AddTodos;
When clicked Submit it's giving this error:

I recreate your api call and got this response:
await fetch('https://5fa97367c9b4e90016e6a7ec.mockapi.io/api/todos', {
method: 'POST', body: JSON.stringify({id: "123",title: "homework", isDone: false, user: "foo"})})
.then(response => response.json())
.then(data => {
console.log(data)
})
error 400 "Max number of elements reached for this resource!"
you need to delete some records in order to insert new ones
so after deleting a record:
await fetch('https://5fa97367c9b4e90016e6a7ec.mockapi.io/api/todos/1', {
method: 'DELETE'})
.then(response => response.json())
.then(data => {
console.log(data)
})
VM623:5 {id: "1", title: "deneme", isDone: true, user: "cafererensimsek"}
and posting a new one, now it works

Related

React time based function

I am trying to create an api post function that sends when the timeout reaches 45 seconds and when the user clicks the cancel button the post request stops or you clear the timeout to stop it.
I did something that works but after another 45 secs it makes another post requirement. is there way to make the post request after the 45 seconds and then cancel the request when user clicks the cancel button
import { makeStyles } from "#material-ui/core/styles";
import styles from "styles/jss/nextjs-material-kit/pages/components.js";
import Button from "components/CustomButtons/Button.js";
import Time from "components/Time.js"
import { withRouter } from 'next/router'
const useStyles = makeStyles(styles);
function processorder({ query: { name, number, location, ordermessage, price, } }) {
const classes = useStyles();
const [processed, setProcessed] = useState(false)
const [canceled, setCanceled] = useState(false)
const [time, setTime] = useState()
const [data, setData] = useState({})
const Id = setTimeout(() => {
const requestOptions = {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
'Api-key': 'ml7h7L8nN8Q2yA',
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "X-Requested-With"
},
body: JSON.stringify({
client: name,
client_phone: number,
restaurant: "Chitis",
location: location,
ordermessage: "Jollof Rice",
amount: "500"
})
};
fetch('https://munche-bot.herokuapp.com/api/v1/orders', requestOptions)
.then(response => response.json())
.then(result => {
console.log(result)
setData(result.data)
setProcessed(true);
return () => clearTimeout(Id)
})
.catch(error => console.log('error', error));
}, 45000);
const cancel = () => {
clearTimeout(Id);
setCanceled(true);
if (canceled == true) {
alert("canceled")
}
};
return (
<div>
<h3> processing Order<h3>
(processed == false ? (<h3>proceed to payment in <Time/> <h3>) : (<h3>processed proceeding to payment</h3>)
(canceled == false ? (<Button onClicK={cancel} />) : <h3>order canceled</h3>
</div>
)
}
processorder.getInitialProps = ({ query }) => {
return { query }
};
export default processorder
You could wrap your whole timeout function in an if, which is dependant on state. However, this isn't very robust as changing the data or the time also sends a duplicate request:
import { makeStyles } from "#material-ui/core/styles";
import styles from "styles/jss/nextjs-material-kit/pages/components.js";
import Button from "components/CustomButtons/Button.js";
import Time from "components/Time.js"
import { withRouter } from 'next/router'
const useStyles = makeStyles(styles);
function processorder({ query: { name, number, location, ordermessage, price, } }) {
const classes = useStyles();
const [processed, setProcessed] = useState(false)
const [canceled, setCanceled] = useState(false)
const [time, setTime] = useState()
const [data, setData] = useState({})
if (!canceled && !processed) {
const Id = setTimeout(() => {
const requestOptions = {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
'Api-key': 'ml7h7L8nN8Q2yA',
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "X-Requested-With"
},
body: JSON.stringify({
client: name,
client_phone: number,
restaurant: "Chitis",
location: location,
ordermessage: "Jollof Rice",
amount: "500"
})
};
fetch('https://munche-bot.herokuapp.com/api/v1/orders', requestOptions)
.then(response => response.json())
.then(result => {
console.log(result)
setData(result.data)
setProcessed(true);
return () => clearTimeout(Id)
})
.catch(error => console.log('error', error));
}, 45000);
}
const cancel = () => {
clearTimeout(Id);
setCanceled(true);
if (canceled == true) {
alert("canceled")
}
};
return (
<div>
<h3> processing Order<h3>
(processed == false ? (<h3>proceed to payment in <Time/> <h3>) : (<h3>processed proceeding to payment</h3>)
(canceled == false ? (<Button onClicK={cancel} />) : <h3>order canceled</h3>
</div>
)
}
processorder.getInitialProps = ({ query }) => {
return { query }
};
export default processorder
It would probably be better for you to do the whole fetch & timeout inside a clickHandler, with the timeout checking that canceled is false before sending the request.
import { makeStyles } from "#material-ui/core/styles";
import styles from "styles/jss/nextjs-material-kit/pages/components.js";
import Button from "components/CustomButtons/Button.js";
import Time from "components/Time.js"
import { withRouter } from 'next/router'
const useStyles = makeStyles(styles);
function processorder({ query: { name, number, location, ordermessage, price, } }) {
const classes = useStyles();
const [processed, setProcessed] = useState(false)
const [canceled, setCanceled] = useState(false)
const [time, setTime] = useState()
const [data, setData] = useState({})
const [id, setId] = useState()
const cancel = () => {
clearTimeout(id);
setCanceled(true);
if (canceled == true) {
alert("canceled")
}
};
useEffect(() => {
const Id = setTimeout(() => {
const requestOptions = {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
'Api-key': 'ml7h7L8nN8Q2yA',
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "X-Requested-With"
},
body: JSON.stringify({
client: name,
client_phone: number,
restaurant: "Chitis",
location: location,
ordermessage: "Jollof Rice",
amount: "500"
})
};
fetch('https://munche-bot.herokuapp.com/api/v1/orders', requestOptions)
.then(response => response.json())
.then(result => {
console.log(result)
setData(result.data)
setProcessed(true);
clearTimeout(Id);
})
.catch(error => console.log('error', error));
}, 45000);
setId(Id);
console.log(data)
}, []);
return (
<div>
<h3> processing Order<h3>
(processed == false ? (<h3>proceed to payment in <Time/> <h3>) : (<h3>processed proceeding to payment</h3>)
(canceled == false ? (<Button onClicK={cancel} />) : <h3>order canceled</h3>
</div>
)
}
processorder.getInitialProps = ({ query }) => {
return { query }
};
export default processorder

How can I POST data using API from REACTJS?

This is my react code here I want to POST Data using postPoll API and update polls state but I am not understand how can do that.
please help..! please help..!please help..!please help..!please help..!please help..!please help..! at line number 33, 34 ( handalchange )
import React, { useState, useEffect } from "react";
import Poll from "react-polls";
import "../../styles.css";
import { isAutheticated } from "../../auth/helper/index";
import { getPolls, postPoll } from "../helper/coreapicalls";
import axios from "axios";
import { API } from "../../backend";
const MainPoll = () => {
const userId = isAutheticated() && isAutheticated().user._id;
const [polls, setPoll] = useState([]);
const [error, seterror] = useState(false);
useEffect(() => {
loadPoll();
}, []);
const loadPoll = () => {
getPolls().then((data) => {
if (data.error) {
seterror(data.error);
} else {
setPoll(data);
console.log(data);
}
});
};
// Handling user vote
// Increments the votes count of answer when the user votes
const handalchange = async (pollId, userId, answer) => {
console.log(pollId); // getting
console.log(userId); // getting
console.log(answer); // getting
await axios.post(`${API}/vote/${pollId}`, userId, answer);
// postPoll(pollId, { userId, vote }).then(() => {
// loadPoll();
// });
};
return (
<div className="">
<div className="container my-5">
<h1 className="blog_heading my-3">Poll's of the Day</h1>
<div className="row">
{polls.reverse().map((poll, index) => (
<div className="col-lg-4 col-12 poll_border" key={index}>
<Poll
noStorage
question={poll.question}
answers={Object.keys(poll.options).map((key) => {
return {
option: key,
votes: poll.options[key].length,
};
})}
onVote={
(answer) =>
handalchange(poll._id, userId, answer, console.log(answer)) // getting vote
}
className="mb-2"
/>
</div>
))}
</div>
</div>
</div>
);
};
export default MainPoll;
this is my frontend-
POSTMAN - request = >
and here is my backend API -
// post
export const postPoll = (pollId, post) => {
return fetch(`${API}/vote/${pollId}`, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(post),
})
.then((response) => {
return response.json();
})
.catch((err) => console.log(err));
};
It depends on what object does onVote event from Poll component pass. But if it's vote object, that's required in postPoll method as second arguement, than:
function in onVote event should pass poll.id from this component and vote object from Vote component onVote event itself:
onVote={(vote) => handalchange(poll.id, vote)}
handalchange should fire postPoll api method with these arguements and load updated poll data on success:
const handalchange = (pollId, vote) => {
postPoll(pollId, vote).then(() => {
loadPoll();
});
}

.then promise not working within axios delete request in react application

I am trying to call a function to fetch data from the database upon deleting a note. This is so that the array of notes can be updated to reflect the deleted note. The function where the error occurs is called deleteNote and the function I am trying to call within the .then promise is getNotes.
Below is the code in my App.js file. If someone could help me solve this I'd greatly appreciate it.
import React, { useEffect, useState } from 'react';
import axios from 'axios';
// import HighlightOffIcon from '#material-ui/icons/HighlightOff';
import './App.css';
const App = () => {
const [note, setNote] = useState('');
const [notesList, setNotesList] = useState([]);
const getNotes = () => {
axios.get('http://localhost:8080/api')
.then((res) => setNotesList(res.data))
.catch(() => alert('Error recieving data.'));
}
useEffect(() => {
getNotes();
}, [])
const handleChange = (event) => {
const content = event.target.value;
setNote(content);
}
const handleSubmission = (event) => {
event.preventDefault();
axios({
url: 'http://localhost:8080/api/save',
method: 'POST',
data: {
content: note
}
})
.then((res) => {
console.log('Created Note');
setNote('');
getNotes();
})
.catch(() => {
console.log('Internal server error');
})
}
const deleteNote = (event) => {
const value = event.target.value;
axios({
method: 'DELETE',
url: 'http://localhost:8080/api/delete',
data: {
_id: value
}
})
.then(() => {
console.log('Note Deleted');
getNotes(); //Where the notes should be fetched upon successful deletion.
})
.catch(() => {
alert('Error deleting note.');
});
}
return (
<div className="app">
<h1>React Notes App</h1>
<form onSubmit={handleSubmission}>
<input
type="text"
placeholder="Enter note"
value={note}
onChange={handleChange}
/>
<button className="submit-button">Submit</button>
</form>
<div className="notes-list">
{notesList.map((note, index) => {
return (
<div className="note" key={index}>
<p>{note.content}</p>
<button value={note._id} className="delete-button" onClick={deleteNote}><i className="fas fa-trash-alt"></i></button>
</div>
);
})}
</div>
</div>
);
}
export default App;
I figured out the issue. When sending a request with axios, you must have a response sent back from the server in order to execute any code you may have in the promise.
example server code:
app.delete('/delete', (req, res) => {
BlogPost.delete({_id: req.body.id}, (err) => {
if (err) {
console.log(err);
} else {
console.log('Successfully deleted blog post.')
res.json({ //Must include a response to execute code within the axios promise.
msg: 'Delete request was recieved.'
});
}
});
});

Reach router refresh page

Setup:
I have a form that send data to an action creator, which in turn submits to an API and gets the result. What I want is when the form submits successfully, to refresh the form with blank inputs.
This is how the component looks like
import React, { Component } from "react";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import { addNewProduct } from "../../redux/actions";
class Admin extends Component {
state = {
ProductName: ""
};
onChange = e => {
e.preventDefault()
this.setState({
[e.target.name]: e.target.value
})
}
handleProductSubmit = (event) => {
event.preventDefault();
this.props.addNewProduct(
this.state.ProductName,
);
}
render() {
return (
<div>
{/* Form ends */}
<form onSubmit={this.handleProductSubmit} autoComplete="off">
<input
type="text"
value={this.state.ProductName}
name="ProductName"
onChange={this.onChange}
/>
<button type="submit" className="btn btn-dark">
Upload Product
</button>
</form>
{/* Form Ends */}
</div>
);
}
}
const mapDispatchToProps = (dispatch) => {
return bindActionCreators({ addNewProduct, createNewLogin }, dispatch);
};
export default connect(null, mapDispatchToProps)(Admin);
This is the result of the console.log(this.props)
location: Object { pathname: "/Home/admin", href: "http://localhost:3000/Home/admin", origin: "http://localhost:3000", … }
navigate: navigate(to, options)
​​
length: 2
​​
name: "navigate"
​​
prototype: Object { … }
​​
<prototype>: ()
This is how the actionCreator looks like
export const addNewProduct = (ProductName, ProductCategory, ProductImg) => (dispatch) => {
const productData = new FormData();
productData.append("ProductName", ProductName)
axios.post("http://localhost:4500/products/", productData,
{
headers: {
"Content-Type": "multipart/form-data",
"Authorization": localStorage.getItem("Authorization")
}
})
.then(res => {
console.log(res.data)
setTimeout(() => {
console.log("doing the timeout")
navigate("/Home/admin")}, 1500);
})
.catch(err =>
console.log(`The error we're getting from the backend--->${err}`))
};
Current behavior
When I submit the form and the API return 201, the page does not refresh and the inputs do not go blank
Expected behavior:
When I get a 201 from the API, the page should refresh and the inputs should be blank.
Please help me how to achieve this.
Using navigate to move the same url or page won't remount the page and reset your field values.
Its better is you actually return a promise from your action creator and reset the state yourself
export const addNewProduct = (ProductName, ProductCategory, ProductImg) => (dispatch) => {
const productData = new FormData();
productData.append("ProductName", ProductName)
return axios.post("http://localhost:4500/products/", productData,
{
headers: {
"Content-Type": "multipart/form-data",
"Authorization": localStorage.getItem("Authorization")
}
})
.then(res => {
console.log(res.data)
})
.catch(err =>
console.log(`The error we're getting from the backend--->${err}`))
};
In the component
handleProductSubmit = (event) => {
event.preventDefault();
this.props.addNewProduct(
this.state.ProductName,
).then(() => {
this.setState({ProductName: ""})
});
}

Converting functions from pure react to redux react

In pure react, I have written a function that I call in componentDidMount ():
getTasks = (userId, query, statusTask, pageNumber) => {
let check = {};
axios({
url: `/api/v1/beta/${userId}`,
method: 'GET'
})
.then(res => {
check = res.data;
if (res.data) {
this.setState({
checkRunning: res.data,
checkRunningId: res.data.id
});
this.utilizeTimes(res.data.task_id);
}
})
.catch(error => {
console.log(error);
})
.then(() => {
const params = {
sort: 'name'
};
if (query) {
params['filter[qwp]'] = query;
if (this.state.tasks[0]) {
this.setState({
selectedId: this.state.tasks[0].id,
selectedTabId: this.state.tasks[0].id
});
}
}
axios({
url: '/api/v1//tasks',
method: 'GET',
params
})
.then(res => {
if (res.status === 200 && res.data) {
this.setState({
tasks: res.data,
lengthArrayTasks: parseInt(res.headers['x-pagination-total-count'])
});
if (!check && res.data && res.data[0]) {
this.setState({
selectedTabId: res.data[0].id,
});
this.load(res.data[0].id);
}
let myArrayTasks = [];
myArrayTasks = res.data;
let findObject = myArrayTasks.find(task => task.id === this.state.runningTimerTask.id);
if (
!findObject &&
this.state.runningTimerTask &&
this.state.runningTimerTask.id &&
this.state.query === ''
) {
this.setState({
tasks: [this.state.runningTimerTask, ...myArrayTasks]
});
}
}
})
.catch(error => {
console.log(error);
});
});
};
I am trying to rewrite it to redux, but with poor results. First it makes one request / api / v1 / beta / $ {userId}, writes the answer in the variable check. check passes to the nextthen. In the next then carries out the request '/ api / v1 // tasks' Can somebody help me? I am asking for some tips. Is this somehow complicated?
So far, I've managed to create something like this:
store
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from '../reducers';
const store = createStore(rootReducer, applyMiddleware(thunk));
export default store;
actions
export const RUNNING_TIMER = 'RUNNING_TIMER';
export const GET_TASKS = 'GET_TASKS';
export const FETCH_FAILURE = 'FETCH_FAILURE';
export const runningTimer = (userId, query, statusTask, pageNumber) => dispatch => {
console.log(userId);
axios({
url: `/api/v1/beta/${userId}`,
method: 'GET'
})
.then(({ data }) => {
dispatch({
type: RUNNING_TIMER,
payload: data
});
})
.catch(error => {
console.log(error);
dispatch({ type: FETCH_FAILURE });
})
.then(() => {
const params = {
sort: 'name'
};
axios({
url: '/api/v1//tasks',
method: 'GET',
params
})
.then(({ data }) => {
dispatch({
type: GET_TASKS,
payload: data
});
})
.catch(error => {
console.log(error);
});
});
};
reducer
import { RUNNING_TIMER, GET_TASKS } from '../actions';
const isRunningTimer = (state = {}, action) => {
const { type, payload } = action;
switch (type) {
case RUNNING_TIMER:
return {
checkRunningTimer: payload,
checkRunningTimerId: payload && payload.id ? payload.id : null
};
break;
case GET_TASKS:
return {
tasks: payload,
lengthArrayTasks: parseInt(action.headers['x-pagination-total-count'])
};
default:
return state;
}
};
const rootReducer = combineReducers({ isRunningTimer });
export default rootReducer;
App
class App extends Component {
constructor() {
super();
this.state = {
name: 'React'
};
}
componentDidMount() {
this.props.runningTimer();
}
render() {
return (
<div>
</div>
);
}
}
const mapStateToProps = state => {
const { isRunningTimer } = state;
return {
isRunningTimer
};
};
const mapDispatchToProps = dispatch => ({
runningTimer: (userId, query, statusTask, pageNumber) => dispatch(runningTimer()),
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(App);
Number 1 Consider your state design.
I find it useful to consider what the state object would look like at a given point in time.
Here is an example of initialState used in an application of mine.
const initialState = {
grocers: null,
coords: {
latitude: 37.785,
longitude: -122.406
}
};
This is injected at the createStore.
Breaking down your application state object/properties, should assist you in making your actions simpler as well.
Number 2
Consider breaking down your actions.
My thoughts, decouple the action code, at the .then at the second .then .(Consider saving the results somewhere in a user: object)
.then(response => {
const data = response.data.user;
setUsers(data);})
.catch(error => {
console.log('There has been a problem with your fetch operation: ' + error.message);
})
function setUsers(data){
dispatch({
type: FETCH_USERS,
payload: data
});
}
This refers to the S in SOLID design principles. Single Responsibility Principle.
https://devopedia.org/solid-design-principles
Number 3
Consider this, if the 'getUser' info fetch fails.
Having the process/response separated will allow the application to be debugged more cleanly. In example, the user api failed or the getTask api failed, etc.
More resources on redux.
https://redux.js.org/introduction/learning-resources#thinking-in-redux
Extending previous answer from #Cullen, this is what I did:
Since you already have a action to GET_TODOS, just make the action creator for runningTimer to do one and only one thing - make API call to /api/v1/beta/<userId> and dispatch respective actions.
export const runningTimer = (
userId,
query,
statusTask,
pageNumber
) => dispatch => {
return axios({
url: `/api/v1/beta/${userId}`,
method: "GET"
})
.then(({ data }) => {
dispatch({
type: RUNNING_TIMER,
payload: data
});
})
.catch(error => {
console.log(error);
dispatch({ type: FETCH_FAILURE });
});
};
Update props of your app component to read store data.
...
const mapStateToProps = state => {
const { isRunningTimer, todos, todo } = state;
return {
todos,
todo,
isRunningTimer,
};
};
const mapDispatchToProps = dispatch => ({
getTodos: () => dispatch(getTodos()),
getTodo: id => dispatch(getTodo(id)),
runningTimer: (userId, query, statusTask, pageNumber) => dispatch(runningTimer(userId)),
});
...
Update the implementation of componentDidMount to dispatch isRunningTimer -
componentDidMount() {
...
// call with userId 1
this.props.runningTimer(1).then(() => {
console.log(this.props);
// additional params for getTasks
const params = {
sort: 'name'
};
// another call for getTodos with names sorted
this.props.getTodos(params);
});
...
Note: You need to update your getTodos action to take in an optional params arguments (which is initialized to empty object if not passed).
Hope this helps you.
Live sandbox for this is present here - https://stackblitz.com/edit/react-redux-more-actions
Check out React-boilerplate. Great boilerplate for react and redux. They use redux-saga and redux-hooks as well.

Categories

Resources