How to make a POST API call in React? - reactjs

I am creating a react program for front-end which makes a api call when a form is submitted, I want the contents of the form to be sent in JSON format
Back-end code works fine, back-end is written in python and it works fine when I test using postman.
import React, { Component } from "react"
class MainCon extends Component {
constructor() {
super()
this.state = {
systemId: "",
password: "",
systemType: "",
ip: "",
portNumber: "",
sourceAddressTon: "",
sourceAddressNpi: "",
sourceAddress: "",
destinationAddressTon: "",
destinationAddressNpi: "",
destinationAddress: "",
registeredDelivery: "",
dataCoding: "",
shortMessage: "",
id: "",
//isFriendly: false,
messageMethod: "",
//favColor: "blue"
}
this.handleChange = this.handleChange.bind(this)
}
handleChange(event) {
//const {name, value, type, checked} = event.target
// type === "checkbox" ? this.setState({ [name]: checked }) : this.setState({ [name]: value })
const { name, value } = event.target
this.setState({ [name]: value })
}
handleSubmit(event) {
event.preventDefault();
const data = new FormData(event.target);
console.log(event.target);
let object = {}
for (const [key, value] of data.entries()) {
object[key] = value
}
/*
const headers = new Headers();
headers.append('Content-Type', 'application/json');
const options = {
method: 'POST',
headers,
body: JSON.stringify(object),
};
const request = new Request('http://127.0.0.1:5000/api/add_message', options);
const response = fetch(response);
const status = response.status;
if (status === 201) {
this.fetchAll()
}
*/
fetch('http://127.0.0.1:5000/api/add_message/', {
headers: {
'Content-Type': 'application/json',
},
method: 'POST',
body: JSON.stringify(object),
});
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<br />
<label htmlFor="systemId">System ID</label>
<input
type="text"
value={this.state.systemId}
name="systemId"
placeholder="System ID"
onChange={this.handleChange}
/>
<br />
<br />
<label htmlFor="password">Password:</label>
<input
type="text"
value={this.state.password}
name="password"
placeholder="Password"
onChange={this.handleChange}
/>
<br />
<br />
<label htmlFor="systemType">System Type:</label>
<input
type="text"
value={this.state.systemType}
name="systemType"
placeholder="System Type"
onChange={this.handleChange}
/>
<br />
<br />
<label htmlFor="ip">IP:</label>
<input
type="text"
value={this.state.ip}
name="ip"
placeholder="IP"
onChange={this.handleChange}
/>
<br />
<br />
<label htmlFor="portNumber">Port Number:</label>
<input
type="text"
value={this.state.portNumber}
name="portNumber"
placeholder="Port Number"
onChange={this.handleChange}
/>
<br />
<br />
<label htmlFor="sourceAddressTon">Source Address Ton:</label>
<input
type="text"
value={this.state.sourceAddressTon}
name="sourceAddressTon"
placeholder="Source Address Ton"
onChange={this.handleChange}
/>
<br />
<br />
<label htmlFor="sourceAddressNpi">Source Address Npi:</label>
<input
type="text"
value={this.state.sourceAddressNpi}
name="sourceAddressNpi"
placeholder="Source Address Npi"
onChange={this.handleChange}
/>
<br />
<br />
<label htmlFor="sourceAddress">Source Address:</label>
<input
type="text"
value={this.state.sourceAddress}
name="sourceAddress"
placeholder="Source Address"
onChange={this.handleChange}
/>
<br />
<br />
<label htmlFor="destinationAddressTon">Destination Address Ton:</label>
<input
type="text"
value={this.state.destinationAddressTon}
name="destinationAddressTon"
placeholder="Destination Address Ton"
onChange={this.handleChange}
/>
<br />
<br />
<label htmlFor="destinationAddressNpi">Destination Address Npi:</label>
<input
type="text"
value={this.state.destinationAddressNpi}
name="destinationAddressNpi"
placeholder="Destination Address Npi"
onChange={this.handleChange}
/>
<br />
<br />
<label htmlFor="destinationAddress">Destination Address:</label>
<input
type="text"
value={this.state.destinationAddress}
name="destinationAddress"
placeholder="Destination Address"
onChange={this.handleChange}
/>
<br />
<br />
<label htmlFor="registeredDelivery">Registered Delivery:</label>
<input
type="text"
value={this.state.registeredDelivery}
name="registeredDelivery"
placeholder="Registered Delivery"
onChange={this.handleChange}
/>
<br />
<br />
<label htmlFor="dataCoding">Data Coding:</label>
<input
type="text"
value={this.state.dataCoding}
name="dataCoding"
placeholder="Data Coding"
onChange={this.handleChange}
/>
<br />
<br />
<label>
<input
type="radio"
name="messageMethod"
value="randomMessage"
checked={this.state.messageMethod === "randomMessage"}
onChange={this.handleChange}
/> Random Message
</label>
<label>
<input
type="radio"
name="messageMethod"
value="customMessage"
checked={this.state.messageMethod === "customMessage"}
onChange={this.handleChange}
/> Custom Message
</label>
<br />
<br />
<label htmlFor="shortMessage">Short Message:</label>
<textarea
//className="hideDontTakeUpSpace"
value={this.state.shortMessage}
name="shortMessage"
placeholder="Short Message"
onChange={this.handleChange}
/>
<br />
{/* Formik */}
{/**
<label>Favorite Color:</label>
<select
value={this.state.favColor}
onChange={this.handleChange}
name="favColor"
<option value="blue">Blue</option>
<option value="green">Green</option>
<option value="red">Red</option>
<option value="orange">Orange</option>
<option value="yellow">Yellow</option>
</select>
*/}
{/*<h1>{this.state.systemId} {this.state.password}</h1>*/}
<h2>Type of message: {this.state.messageMethod}</h2>
{/*<h2>Your favorite color is {this.state.favColor}</h2>*/}
<button>Submit</button>
</form>
)
}
}
export default MainCon
This is the server side python code
import requests
import json
from flask import Flask, request, jsonify
from jsonDemoNew import getMemberNew
import redis
app = Flask(__name__)
#app.route('/api/add_message', methods=['GET', 'POST'])
def add_message():
if request.method == 'POST':
content = request.json
print request
print content
return jsonify({"Number of messages sent": 123, "Printed status" : 1})
return "Not POST request"
if __name__ == "__main__":
app.run()
I think there is some problem with the headers I am including

I personally prefer to use axios to make POST requests.
npm install axios --save
Just like on postman:
Select the method ('post' in that case)
Select the url ('http://127.0.0.1:5000/api/add_message/')
Send theData in "json form" like:
{
"data": "oktay"
}
And it's done:
const axios = require('axios');
const postIt = (theData) => {
axios({
method: 'post', // THERE GOES THE METHOD
url: 'http://127.0.0.1:5000/api/add_message/', // THERE GOES THE URL
headers: {},
data: theData
})
.then(function (response) {
console.log("The response of the server: "+response.data);
})
.catch(function (error) {
// handle error
console.log(error);
})
.finally(function () {
// always executed
});
}
postIt({
"data" : "oktay"
});

Related

unable to use fetch in formik and post data to api

I was trying to post the formik form data using fetch and mutations. I have created my API using neo4j graphql library and Apollo server now i want to post data into the API using react as frontend.
import './App.css';
import { useFormik } from "formik"
function App() {
const updateNameFetch = async (name,age,sex,weight,smoking,drinking,nationality,birth_type) => {
const query = JSON.stringify({
query: `mutation {
createUsers(input:{
user_name: "${name}"
age: ${age}
sex: "${sex}"
weight: ${weight}
smoking:"${smoking}"
drinking: "${drinking}"
nationality:"${nationality}"
birth_type: "${birth_type}"
}
){
users{
user_name
}
}
}
`
});
const formik = useFormik({
initialValues:{
name:"",
age: "",
sex: "",
weight:"",
smoking:"",
drinking:"",
nationality:"",
birth_type:"",
},
onSubmit:(values) => {
console.log(values.name);
fetch("graphql-newone.herokuapp.com/",{
method: "POST",
headers: {"Content-Type": "application/json"},
body: query,
})
}
})
return (
<div className="App">
<form onSubmit={formik.handleSubmit}>
<div className='input-container'>
<input
id="name"
name="name"
type="text"
placeholder="Name"
onChange={formik.handleChange}
value = {formik.values.name}
/>
<input
id="sex"
name="sex"
type="text"
placeholder="Sex"
onChange={formik.handleChange}
value = {formik.values.sex}
/>
<input
id="age"
name="age"
type="text"
placeholder="Age"
onChange={formik.handleChange}
value = {formik.values.age}
/>
<input
id="weight"
name="weight"
type="text"
placeholder="weight"
onChange={formik.handleChange}
value = {formik.values.weight}
/>
<input
id="smoking"
name="smoking"
type="text"
placeholder="smoking"
onChange={formik.handleChange}
value = {formik.values.smoking}
/>
<input
id="nationality"
name="nationality"
type="text"
placeholder="nationality"
onChange={formik.handleChange}
value = {formik.values.nationality}
/>
<input
id="birth_type"
name="birth_type"
type="text"
placeholder="birth_type"
onChange={formik.handleChange}
value = {formik.values.birth_type}
/>
</div>
<button type="submit">Submit</button>
</form>
</div>
);
}}
export default App;
I am getting this error and unable to rectify it
Line 28:18: React Hook "useFormik" is called in function "updateNameFetch" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter. React Hook names must start with the word "use" react-hooks/rules-of-hooks
Search for the keywords to learn more about each error.
As it says, you cant use the useFormik hook inside the function
import './App.css';
import { useFormik } from "formik"
function App() {
const postData = async(query)=>{
let res = await fetch("graphql-newone.herokuapp.com/",{
method: "POST",
headers: {"Content-Type": "application/json"},
body: query,
})
let data = await res.json()
console.log(data)
}
const formik = useFormik({
initialValues:{
name:"",
age: "",
sex: "",
weight:"",
smoking:"",
drinking:"",
nationality:"",
birth_type:"",
},
onSubmit:async(values) => {
let query = JSON.stringify({
query: `mutation {
createUsers(input:{
user_name: "${values.name}"
age: ${values.age}
sex: "${values.sex}"
weight: ${values.weight}
smoking:"${values.smoking}"
drinking: "${values.drinking}"
nationality:"${values.nationality}"
birth_type: "${values.birth_type}"
}
){
users{
user_name
}
}
}
`
});
postData(query)
}
})
return (
<div className="App">
<form onSubmit={formik.handleSubmit}>
<div className='input-container'>
<input
id="name"
name="name"
type="text"
placeholder="Name"
onChange={formik.handleChange}
value = {formik.values.name}
/>
<input
id="sex"
name="sex"
type="text"
placeholder="Sex"
onChange={formik.handleChange}
value = {formik.values.sex}
/>
<input
id="age"
name="age"
type="text"
placeholder="Age"
onChange={formik.handleChange}
value = {formik.values.age}
/>
<input
id="weight"
name="weight"
type="text"
placeholder="weight"
onChange={formik.handleChange}
value = {formik.values.weight}
/>
<input
id="smoking"
name="smoking"
type="text"
placeholder="smoking"
onChange={formik.handleChange}
value = {formik.values.smoking}
/>
<input
id="nationality"
name="nationality"
type="text"
placeholder="nationality"
onChange={formik.handleChange}
value = {formik.values.nationality}
/>
<input
id="birth_type"
name="birth_type"
type="text"
placeholder="birth_type"
onChange={formik.handleChange}
value = {formik.values.birth_type}
/>
</div>
<button type="submit">Submit</button>
</form>
</div>
);
}
export default App;

Getting bad request error on forn submission in react

This the component I created. I can get the contact in console but throws error on submission. I can post the data through Postman; the problem occurs when I submit the form. Where is the error in the handlesubmit function?
import axios from 'axios';
import React, { useState } from 'react';
const ContactForm = () => {
const [contact, setContact] = useState({
firstName: '',
lastName: '',
phoneNumber: '',
email: '',
message: '',
});
function handleChange(e) {
setContact({ ...contact, [e.target.name]: [e.target.value] });
}
function hanhdleSubmit(e) {
e.preventDefault();
console.log(contact);
axios
.post('http://localhost:8080/contact', contact)
.then((response) => {
console.log('Response after post api', response.data);
})
.catch((error) => {
console.log('Error while post api', error);
});
}
return (
<div className="box poptrox-popup ">
<form onSubmit={hanhdleSubmit} noValidate>
<div className="row gtr-uniform">
<div className="col-6 col-12-xsmall">
<input
type="text"
placeholder="First Name"
value={contact.firstName}
name="firstName"
onChange={handleChange}
autoComplete="off"
/>
<br />
</div>
<div className="col-6 col-12-xsmall">
<input
type="text"
placeholder="Last Name"
value={contact.lastName}
name="lastName"
onChange={handleChange}
autoComplete="off"
/>
<br />
</div>
<div className="col-6 col-12-xsmall">
<input
type="tel"
placeholder="Phone Number"
value={contact.phoneNumber}
name="phoneNumber"
onChange={handleChange}
autoComplete="off"
/>
<br />
</div>
<div className="col-6 col-12-xsmall">
<input
type="email"
placeholder="Email"
value={contact.email}
name="email"
onChange={handleChange}
autoComplete="off"
/>
<br />
</div>
<div className="col-6 col-12-xsmall">
<textarea
placeholder="Please type what you are looking from us?"
value={contact.message}
name="message"
onChange={handleChange}
/>
<br />
</div>
<div className="col-12">
<button type="submit">Submit</button>
<h1>First Name:{contact.firstName}</h1>
<h1>Last Name:{contact.lastName}</h1>
<h1>Phone Number:{contact.phoneNumber}</h1>
<h1>Email:{contact.email}</h1>
<h1>message:{contact.message}</h1>
</div>
</div>
</form>
</div>
);
};
export default ContactForm;
This is the error I'm getting:
{
"timestamp": "2020-12-04T18:32:39.945+00:00",
"status": 400,
"error": "Bad Request",
"message": "",
"path": "/contact"
}
I think it's the syntax of the body sent to the backend, the second parameter of your axios.post should be an object :
axios
.post('http://localhost:8080/contact', contact)
should be
axios
.post('http://localhost:8080/contact', { contact })

How to redirect to profile page in React after submitting Login and Signup button?

Here is my code for my login page that I want to use to redirect onto a profile page:
import React, { Component } from "react";
export default class Login extends Component {
constructor(props){
super(props)
this.state = {
username: '',
password: '',
}
}
handleChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
}
handleSubmit = (e) => {
e.preventDefault();
const {username, password} = this.state;
fetch('http://localhost:9000/users/login', {
method: "POST",
headers: {
'Content-Type' : 'application/json'
},
body: JSON.stringify(this.state),
})
.then((result) => result.json())
.then((info) => {console.log(info)})
}
render() {
return (
<div className="auth-wrapper">
<div className="auth-inner">
<form onSubmit={this.handleSubmit}>
<h3>Sign In</h3>
<div className="form-group">
<label>Username</label>
<input type="text" className="form-control" placeholder="Enter email" value={this.state.value} onChange={this.handleChange} name="username" />
</div>
<div className="form-group">
<label>Password</label>
<input type="password" name="password" className="form-control" value={this.state.value} onChange={this.handleChange} placeholder="Enter password" />
</div>
<div className="form-group">
<div className="custom-control custom-checkbox">
<input type="checkbox" className="custom-control-input" id="customCheck1" />
<label className="custom-control-label" htmlFor="customCheck1">Remember me</label>
</div>
</div>
<button type="submit" className="btn btn-primary btn-block">Submit</button>
<p className="forgot-password text-right">
Forgot password?
</p>
</form>
</div>
</div>
);
}
}
import React, { Component } from "react";
import { Redirect } from 'react-router';
import { withRouter } from 'react-router';
export default class SignUp extends Component {
constructor(props){
super(props)
this.state = {
firstName: '',
password: '',
username: '',
lastName: '',
email: '',
isAdmin: 'false',
}
}
onChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
console.log(this.state.email)
console.log(this.state.isAdmin)
}
onSubmit = async (e) => {
e.preventDefault();
await this.state.isAdmin == "on" ? this.setState({isAdmin: true}) : this.setState({isAdmin: false})
// const {firstName, lastName, email,} = this.state;
fetch('http://localhost:9000/users/new', {
method: "POST",
headers: {
'Content-Type' : 'application/json'
},
body: JSON.stringify(this.state)
})
.then((info) => {console.log(info)})
this.props.history.push('/profile');
}
render() {
return (
<div className="auth-wrapper">
<div className="auth-inner">
<form method='POST' action='http://localhost:9000/users/new'>
<h3>Sign Up</h3>
<div className="form-group">
<label>First name</label>
<input type="text" className="form-control" placeholder="First name" name ="firstName"/>
</div>
<div className="form-group">
<label>Last name</label>
<input type="text" className="form-control" placeholder="Last name" name="lastName" />
</div>
<div className="form-group">
<label>Username</label>
<input type="text" className="form-control" placeholder="Username" name="username" />
</div>
<div className="form-group">
<label>Email address</label>
<input type="email" className="form-control" placeholder="Enter email" name="email" />
</div>
<div className="form-group">
<label>Password</label>
<input type="password" className="form-control" placeholder="Enter password" name="password" />
</div>
<div className="form-group">
<div className="custom-control custom-checkbox">
<input type="checkbox" className="custom-control-input" onClick={console.log(this.state.value)} name="isAdmin" id="customCheck1" />
<label className="custom-control-label" htmlFor="customCheck1">Signup as Reviewer</label>
</div>
</div>
<button type="submit" className="btn btn-primary btn-block">Sign Up</button>
<p className="forgot-password text-right">
Already registered sign in?
</p>
</form>
</div>
</div>
);
}
}
When I click my profile page I want to redirect to /profile. At the moment it hangs and successfully logs in the user. I have to manually go to /profile to reach the page right now
I am using Express as my backend FYI
Edit: I have added my sign up page code as that is not working also and not sure why. Like the login page it hangs
try this
fetch('http://localhost:9000/users/login', {
method: "POST",
headers: {
'Content-Type' : 'application/json'
},
body: JSON.stringify(this.state),
})
.then((result) => {
result.json();
this.props.history.push("/Profile");})
.then((info) => {console.log(info)})

state undefined: while sending post request from react app

I am new in react and trying to send post request to an api and getting state undefined while sending post request from react app, i this occurs because state stores data as an object. Dont know how to solve this. i would really appreciate some help.
compmonent.js
import React, { Component } from 'react'
class Register extends Component {
register () {
// alert('register')
console.warn('state', this.state)
fetch('http://localhost:8000/api/v1/accounts/registration/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(this.state)
}).then((result) => {
result.json().then((resp) => {
console.log(resp.data.token)
localStorage.setItem('register', JSON.stringify(resp.data.token))
})
})
}
render () {
return (
<div>
<div>
<label>Email</label>
<input
type='text' placeholder='email'
onChange={(e) => { this.setState({ email: e.target.value }) }}
/><br /><br />
<label>First name</label>
<input
type='text' placeholder='first name'
onChange={(e) => { this.setState({ first_name: e.target.value }) }}
/><br /><br />
<label>Last name</label>
<input
type='text' placeholder='last name'
onChange={(e) => { this.setState({ last_name: e.target.value }) }}
/><br /><br />
<label>Password</label>
<input
type='password' placeholder='password'
onChange={(e) => { this.setState({ password1: e.target.value }) }}
/><br /><br />
<label>Confirm password</label>
<input
type='password' placeholder='confirm password'
onChange={(e) => { this.setState({ password2: e.target.value }) }}
/><br /><br />
<button onClick={() => this.register()}>Register</button>
</div>
</div>
)
}
}
export default Register
thanks
Your code looks ok,
I've created a runnable code snippet from your code, only time state is null and not undefined, is when you don't fill-up the form and submit,
for that you can put a condition before making fetch request.
You can run the below code snippet and check :
class App extends React.Component {
register () {
// alert('register')
console.warn('state', this.state)
if (this.state) { // <------ HERE
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
// Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(this.state)
}).then((result) => {
result.json().then((resp) => {
console.log(resp.data.token)
localStorage.setItem('register', JSON.stringify(resp.data.token))
})
})
}
}
render () {
return (
<div>
<div>
<label>Email</label>
<input
type='text' placeholder='email'
onChange={(e) => { this.setState({ email: e.target.value }) }}
/><br /><br />
<label>First name</label>
<input
type='text' placeholder='first name'
onChange={(e) => { this.setState({ first_name: e.target.value }) }}
/><br /><br />
<label>Last name</label>
<input
type='text' placeholder='last name'
onChange={(e) => { this.setState({ last_name: e.target.value }) }}
/><br /><br />
<label>Password</label>
<input
type='password' placeholder='password'
onChange={(e) => { this.setState({ password1: e.target.value }) }}
/><br /><br />
<label>Confirm password</label>
<input
type='password' placeholder='confirm password'
onChange={(e) => { this.setState({ password2: e.target.value }) }}
/><br /><br />
<button onClick={() => this.register()}>Register</button>
</div>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('react-root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react-root"></div>

I need to make a "sign up" request from react front-end to Scala back-end api

I am a new to React.js, currently is doing my university project. Basically, my Sign up api was completed and successfully, but now, how do I call an api to react front end? I have review some of the example from youtube and stackoverfloe, but I still stuck on here. Below I will describe more about my current situation:
Here is api my result I get on postman.
So I have no problem with my API.
Here is how I call my API to react frontend:
handleSubmit(event){
const {
name,
email,
UserMobile,
Password,
confirmPassword,
Organisation_Name,
Address,
description
} = this.state;
console.log(this.state)
axios({
method: 'post',
url: 'http://localhost:9000/api/users/sign-up',
data: {
name: name,
email: email,
UserMobile: UserMobile,
Password: Password,
confirmPassword: confirmPassword,
Organisation_Name: Organisation_Name,
Address: Address,
description: description
},
}).catch(error => {
console.log(error);
}).then(response => {
console.log(response);
});
}
Here is some source code of :
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<input
type="type"
name="name"
placeholder="name"
value={this.state.name || ''}
onChange={this.handleChange}
required
/>
<input
type="email"
name="email"
placeholder="email"
value={this.state.email}
onChange={this.handleChange}
required
/>
<input
type="text"
name="UserMobile"
placeholder="UserMobile"
value={this.state.UserMobile || ''}
onChange={this.handleChange}
required
/>
<input
type="Password"
name="Password"
placeholder="Password"
value={this.state.Password || ''}
onChange={this.handleChange}
required
/>
<input
type="Password"
name="confirmPassword"
placeholder="confirmPassword"
value={this.state.confirmPassword || ''}
onChange={this.handleChange}
required
/>
<input
type="Organisation_Name"
name="Organisation_Name"
placeholder="Organisation_Name"
value={this.state.Organisation_Name || ''}
onChange={this.handleChange}
required
/>
<input
type="Address"
name="Address"
placeholder="Address"
value={this.state.Address || ''}
onChange={this.handleChange}
required
/>
<input
type="description"
name="description"
placeholder="description"
value={this.state.description || ''}
onChange={this.handleChange}
required
/>
<button type="Submit">Registration</button>
</form>
</div>
);
}
package.json (in case needed)
"name": "react-redux-router",
"version": "1.0.0",
"description": "Basic skeleton codebase for React/Redux/Router applications.",
"proxy": {
"/connect": {
"target": "http://localhost:9000",
"secure": false,
"changeOrigin": true
}
},
So is it a correct way for react to call the API? and why I cannot get the result as same as postman result? The new user are not enter to the database as well. Hopefully anyone can help me and teach me for this kind of issue.

Resources