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 })
Related
I am trying to test my sign-in form for a react app. Basically the user signs up, and then the form will make an api post request to node.js server that will then post the data into a MySQL databases
The HTML for the form is:
<div className="signup">
<div className="signup__wrapper">
<div className="signup__banner">
<h2 className="signup__logo">Leep</h2>
<h2 className="signup__title">Please Sign Up to find artist</h2>
</div>
<form className="form" onSubmit={handleSubmit} autoComplete='off'>
<div className="form__container">
<input
className={!email.error? `form__input ${email.value? 'form__valid':''}`: "form__input error"}
type='text'
id='email'
data-testid='email'
name='email'
value={email.value}
onChange={handleEmail}
autoComplete='off'
/>
<label className="form__label" htmlFor="email">What's your email?</label>
</div>
<div className="form__container">
<input
className={!confirmEmail.error? `form__input ${confirmEmail.value? 'form__valid':''}`: "form__input error"}
type='text'
id='confirmemail'
data-testid='confirmemail'
name='confirmemail'
value={confirmEmail.value}
onChange={handleConfirmEmail}
/>
<label className="form__label" htmlFor="confirmemail">Please confirm your email?</label>
</div>
<div className="form__container">
<input
className={!username.error? `form__input ${username.value? 'form__valid':''}`: "form__input error"}
type='text'
id='username'
data-testid='username'
name='username'
value={username.value}
onChange={handleUserName}
/>
<label className="form__label" htmlFor="username">What's your user name?</label>
</div>
<div className="form__container">
<input
className={!password.error? `form__input ${password.value? 'form__valid':''}`: "form__input error"}
type='password'
id='password'
name='password'
data-testid='password'
value={password.value}
onChange={handlePassword}
/>
<label className="form__label" htmlFor="password">What's your password?</label>
</div>
<div className="form__container">
<input
className={!confirmPassword.error? `form__input ${confirmPassword.value? 'form__valid':''}`: "form__input error"}
type='password'
id='confirmPassword'
data-testid='confirmPassword'
name='confirmPassword'
value={confirmPassword.value}
onChange={handleConfirmPassword}
/>
<label className="form__label" htmlFor="confirmPassword">Please confirm your password</label>
</div>
<button className="form__btn" type="submit">
Sign up
</button>
<div className="signup__redirect">
<h3 className="signup__redirect--message">Already have an account?</h3>
<Router>
<Link className="signup__redirect--link" to='/login'>
Log in.
</Link>
</Router>
</div>
</form>
</div>
</div>
And here is the code that I am trying to use to test the form submission:
import React from "react";
import ReactDOM from "react-dom";
import SignupPage from "./SignupPage";
import {render, screen, waitFor } from '#testing-library/react'
import user from '#testing-library/user-event'
it("renders without crashing", ()=> {
const div = document.createElement("div")
ReactDOM.render(<SignupPage></SignupPage>, div)
})
describe('SignUpform', () => {
const onSubmit = jest.fn();
window.alert = jest.fn()
beforeEach(() => {
onSubmit.mockClear()
render(<SignupPage onSubmit={onSubmit} />)
});
it('onSubmit is called when all fields pass validation', async () => {
window.alert = () => {};
user.type(getEmail(), 'test#gmail.com')
user.type(confirmEmail(), 'test#gmail.com')
user.type(getUsername(), 'test')
user.type(getPassword(), '1234')
user.type(getConfirmPassword(), '1234')
user.click(screen.getByRole('button'))
await waitFor(() => {
expect(onSubmit).toBeCalledWith({
email: 'test#gmail.com',
confirmemail: 'test#gmail.com',
username: 'test',
password: '1234',
confirmpassword: '1234',
})
expect(onSubmit).toHaveBeenCalledTimes(1)
})
});
})
function getEmail () {
return screen.getByTestId('email', {
name: /email/i
})
}
function confirmEmail () {
return screen.getByTestId('confirmemail', {
name: /confirmemail/i
})
}
function getUsername () {
return screen.getByTestId('username', {
name: /username/i
})
}
function getPassword () {
return screen.getByTestId('password', {
name: /password/i
})
}
function getConfirmPassword() {
return screen.getByTestId('confirmPassword', {
name: /confirmpassword/i
})
}
console out put of the error that is followed by the html elements of the form
here is where the code is stating the error I am not sure what is wrong.
Trying to get a response when clicking and store the selected option from the selected value genre, not sure how to add a select new state variable or a post method. When the option is clicked the click handler is not called with the selected options so that we can add it to the state. My genre is also seen as undefined when I don't click on the the text type.
Feedback.js
import React, { useState } from "react";
import axios from "axios";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.min.css";
import Layout from "./Layout";
const Feedback = () => {
const [values, setValues] = useState({
name: "",
artist: "",
songTitle: "",
email: "",
message: "",
phone: "",
genre: "",
uploadedFiles: [],
buttonText: "Submit",
uploadPhotosButtonText: "Upload files",
});
// destructure state variables
const {
name,
artist,
songTitle,
label,
email,
message,
phone,
genre,
uploadedFiles,
buttonText,
uploadPhotosButtonText,
} = values;
// destructure env variables
const {
REACT_APP_API,
REACT_APP_CLOUDINARY_CLOUD_NAME,
REACT_APP_CLOUDINARY_UPLOAD_SECRET,
} = process.env;
// event handler
const handleChange = (name) => (event) => {
setValues({ ...values, [name]: event.target.value });
};
const handleSubmit = (event) => {
event.preventDefault();
setValues({ ...values, buttonText: "...sending" });
// send to backend for email
console.table({ name, email, phone, message, uploadedFiles, genre });
axios({
method: "POST",
url: `${REACT_APP_API}/feedback`,
data: {
name,
artist,
songTitle,
label,
email,
genre,
phone,
message,
uploadedFiles,
},
})
.then((response) => {
// console.log('feedback submit response', response);
if (response.data.success) toast.success("Thanks for your feedback");
setValues({
...values,
name: "",
artist: "",
songTitle: "",
label: "",
phone: "",
email: "",
genre: "",
message: "",
uploadedFiles: [],
buttonText: "Submitted",
uploadPhotosButtonText: "Uploaded",
});
})
.catch((error) => {
// console.log('feedback submit error', error.response);
if (error.response.data.error) toast.error("Failed! Try again!");
});
};
function onChangeInput(value) {
console.log(value);
}
const uploadWidget = () => {
window.cloudinary.openUploadWidget(
{
cloud_name: REACT_APP_CLOUDINARY_CLOUD_NAME,
upload_preset: REACT_APP_CLOUDINARY_UPLOAD_SECRET,
tags: ["ebooks"],
},
function (error, result) {
// console.log(result);
setValues({
...values,
uploadedFiles: result,
uploadPhotosButtonText: `${
result ? result.length : 0
} Photos uploaded`,
});
}
);
};
const feedbackForm = () => (
<React.Fragment>
<div className="form-group">
<button
onClick={() => uploadWidget()}
className="btn btn-outline-secondary btn-block p-5"
>
{uploadPhotosButtonText}
</button>
</div>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label className="text-muted">Description</label>
<textarea
onChange={handleChange("message")}
type="text"
className="form-control"
value={message}
required
></textarea>
</div>
<div className="form-group">
<label className="text-muted">Your Name</label>
<input
className="form-control"
type="text"
onChange={handleChange("name")}
value={name}
required
/>
</div>
<div className="form-group">
<label className="text-muted">Your Email</label>
<input
className="form-control"
type="email"
onChange={handleChange("email")}
value={email}
required
/>
</div>
<div className="form-group">
<label className="text-muted">Your Phone</label>
<input
className="form-control"
type="number"
onChange={handleChange("phone")}
value={phone}
required
/>
</div>
<div className="form-group">
<label className="text-muted">Artist Name</label>
<input
className="form-control"
type="text"
onChange={handleChange("artist")}
value={artist}
required
/>
</div>
<div className="form-group">
<label className="text-muted">Song Title</label>
<input
className="form-control"
type="text"
onChange={handleChange("songTitle")}
value={songTitle}
required
/>
</div>
<div className="form-group">
<label className="text-muted">Record Label Name</label>
<input
className="form-control"
type="text"
onChange={handleChange("label")}
value={label}
/>
</div>
<div className="form-group">
<label className="text-muted">Music Genre:</label>
<select
className="form-control"
value={genre}
type="select"
onChange={handleChange("genre")}
>
<option value="steak">Steak</option>
<option value="sandwich">Sandwich</option>
<option value="dumpling">Dumpling</option>
</select>
</div>
<button className="btn btn-outline-primary btn-block">
{buttonText}
</button>
</form>
</React.Fragment>
);
return (
<Layout>
<ToastContainer />
<div className="container text-center">
<h1 className="p-5">Feedback Online</h1>
</div>
<div className="container col-md-8 offset-md-2">{feedbackForm()}</div>
<br />
<br />
<br />
</Layout>
);
};
export default Feedback;
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)})
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 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"
});