I'm just learning Vue and I'm making http post request in vue.js and flask as the backend. When I run the program am getting 404 error code. I do not know how to debug the problem but when I test using postman it is working perfect. when I use axios but I am encountering 404.
Below is my frontend code :
<template>
<div>
<h3> {{msg}}</h3>
<p> we help you drive your business with the modern technology. </p>
<div class="alert alert-success" v-if="isSuccess">
Post Created Successfully
</div>
<form #submit.prevent='OnCreateTown' class="add-town">
<div class="form-control">
<label>task</label>
<input type="text" class ="form-control" v-model="text" name="text" placeholder="name" />
<input type="number" step="any" class ="form-control" v-model="text" name="text" placeholder="elevation" />
<input type="text" class ="form-control" v-model="text" name="text" placeholder="grid reference" />
<input type="number" step="any" class ="form-control" v-model="text" name="text" placeholder="longitude" />
<input type="number" step="any" class ="form- control" v-model="text" name="text" placeholder="latitude" />
<input type="text" class ="form- control" v-model="text" name="text" placeholder="postcode_secto" />
<input type="text" class ="form- control" v-model="text" name="text" placeholder="nuts_region" />
<input type="number" step="any" class ="form- control" v-model="text" name="text" placeholder="northing" />
<input type="number" step="any" class ="form- control" v-model="text" name="text" placeholder="easting" />
<input type="text" class ="form- control" v-model="text" name="text" placeholder="town_type" />
<input type="text" class ="form- control" v-model="text" name="text" placeholder="local_government_area" />
</div>
<input type="submit" value="submit" class="btn btn-block" />
</form>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'CreateTown',
props:{
msg: String
},
data(){ // the data expected from the form
return{
form: {
name: '',
elevation: '',
grid_reference: '',
longitude: '',
latitude: '',
postcode_secto:'',
nuts_region:'',
northing:'',
easting :'',
town_type:'',
local_government_area:'',
isSuccess: false,
}
};
},
methods:{
OnCreateTown(){ // when the submit button is clicked, the form data is sent to the backend
axios.post('https://david.darwinist.io/proxy/5000/town.json', this.form)
.then((response) => {// checking response in the console
this.isSuccess = true;
console.log(response.data);
this.$emit('towncreated');
}).catch(err =>{
console.log(err)});
},
},
};
and this is my backend :
def addTown(session, town_dict):
# Try and get the Country from the database. If error (Except) add to the database.
town = Town()
# Add attributes
town.county = addGetCounty(session, town_dict["county"], town_dict["nation"])
town.name = town_dict["name"]
town.grid_reference = town_dict["grid_reference"]
town.easting = town_dict["easting"]
town.northing = town_dict["northing"]
town.latitude = town_dict["latitude"]
town.longitude = town_dict["longitude"]
town.elevation = town_dict["elevation"]
town.postcode_sector = town_dict["postcode_sector"]
town.local_government_area = town_dict["local_government_area"]
town.nuts_region = town_dict["nuts_region"]
town.town_type = town_dict["town_type"]
Related
I have 2 views for adding data to a database, one for songs and one for genres. However, I want to populate the input fields with random data, but I don't know why importing chance in genres, but not in songs, makes songs working, but not genres page.
Genre View:
<template>
<div>
<input type="text" id="genre-name" placeholder="Name" v-model="name" /><br />
<input type="text" id="genre-country" placeholder="Country" v-model="country" /><br />
<input type="text" id="genre-year" placeholder="Year" v-model="year" /><br />
<button #click="addGenre" id="genre-button">Add Genre</button>
</div>
</template>
<script>
import { requestOptions, base_url } from '#/utils/requestOptions';
//var chance = require('chance').Chance(); this works for both, when importing only in one file
import {chance} from "chance"; //<= this is the line I am talking about
export default {
data() {
return {
name: chance.radio(),
country: chance.country({ full: true }),
year: chance.year()
}
},
methods: {
addGenre() {
//...
}
}
}
</script>
Song View:
<template>
<div>
<input type="text" id="name" placeholder="Name" v-model="name" /><br />
<input type="text" id="author" placeholder="Author" v-model="author" /><br />
<input type="text" id="country" placeholder="Country" v-model="country" /><br />
<input type="text" id="duration" placeholder="Duration" v-model="duration" /><br />
<input type="text" id="views" placeholder="Views" v-model="views" /><br />
<input type="text" id="genre" placeholder="Genre" v-model="genre" /><br />
<button #click="addSong">Add Song</button>
</div>
</template>
<script>
import { requestOptions, base_url } from '#/utils/requestOptions';
//this is working without importing chance
export default {
data() {
return {
name: chance.word(),
author: chance.last(),
country: chance.country({ full: true }),
duration: chance.minute(),
views: chance.integer({ min: 0, max: 100000000 }),
genre: chance.radio()
}
},
methods: {
addSong() {
//...
}
}
}
</script>
The error message I am getting when I am opening the Genre View is:
TypeError: undefined is not an object (evaluating 'chance__WEBPACK_IMPORTED_MODULE_1__.chance.radio')
So I want to know why is it working on the Song View?
If I delete the import line, it will not work in any view.
I am trying to send data to my contact form api through react but I am getting this problem
I tried to get input as a value to post through api when clicked on submit button but it is not working
error = the api should call like this https://edu.orgiance.com/api/contactus?secret=xxxxx-ac40-46a0-9c81-d48a1322f4bb&fname=test&email=test#test.com&mobile=8463274946&message=test
but it is calling like this
http://localhost:3000/?name=dfdfsd&email=dsffdsf%40gmail.com&phone=937285294&website=sxascsac&message=dscdscsfgcd#
My Code
import React from 'react';
const ContactForm = (props) => {
const { submitBtnClass } = props;
function handleClick() {
// Send data to the backend via POST
fetch('https://edu.orgiance.com/api/contactus?secret=f1794e34-ac40-46a0-9c81-d48a1322f4bb&fname=test&email=test#test.com&mobile=8463274946&message=', { // Enter your IP address here
method: 'POST',
mode: 'cors',
body: JSON.stringify(jsonData) // body data type must match "Content-Type" header
})
}
var jsonData = {
"contact": [
{
"fname": props.fname,
"email": props.email,
"mobile": props.phone,
"message": props.message
}
]
}
return (
<form id="contact-form" action="#">
<div className="row">
<div className="col-md-6 mb-30">
<input className="from-control" type="text" id="name" name="name" placeholder="Name" value={props.fname} required />
</div>
<div className="col-md-6 mb-30">
<input className="from-control" type="text" id="email" name="email" placeholder="E-Mail" value={props.email} required />
</div>
<div className="col-md-6 mb-30">
<input className="from-control" type="text" id="phone" name="phone" placeholder="Phone Number" value={props.phone} required />
</div>
<div className="col-md-6 mb-30">
<input className="from-control" type="text" id="website" name="website" placeholder="Your Website" required />
</div>
<div className="col-12 mb-30">
<textarea className="from-control" id="message" name="message" placeholder="Your message Here" value={props.message}></textarea>
</div>
</div>
<div className="btn-part" >
<button onClick={handleClick} className={submitBtnClass ? submitBtnClass : 'readon learn-more submit'} type="submit">Submit Now </button>
</div>
</form>
);
}
export default ContactForm;
It looks like you are creating a functional stateless component. That means your data needs to be passed in the props object, and if you are trying to access it anywhere in the ContactForm component, you would need to use this format: props.variablename . ie:
<input className="from-control" type="text" id="name" name="name" placeholder="Name" value={props.fname}required />
All of those variables are undefined. You can't initialize that jsonData object with variables that don't exist, you also can't set <input value={undefinedVariable} ... />
Since you are using form, an easy thing to do is to change it to look something like:
<form onSubmit={this.handleClick}>
...
<input type="submit" value="Submit" />
</form>
Then you can access the form data from the mouse event.
Example:
function handleClick(event) {
event.preventDefault();
const form = event.target;
const jsonData = {
"fname": form.name,
"email": form.email,
"mobile": form.phone,
"message": form.message
};
fetch('https://edu.orgiance.com/api/contactus?secret=f1794exxxxxx',
method: 'POST',
mode: 'cors',
body: JSON.stringify(jsonData)
})
}
I'm using express-validator in a node app. All 4 of my form fields are returning validation errors ("A name is required" and so on). When I console.log the errors variable, all values are blank:
errors: [{value: '', msg: 'A name is required.', param: 'name', location: 'body'},...
Feedback form:
<form class="feedback-form" method="POST" action="/feedback">
<div class="form-group">
<label for="feedback-form-name">Name</label>
<input
type="text"
class="form-control"
id="feedback-form-name"
name="name"
placeholder="Enter your name"
/>
</div>
<div class="form-group">
<label for="feedback-form-email">E-Mail</label>
<input
type="text"
class="form-control"
id="feedback-form-email"
name="email"
placeholder="Enter your email address"
/>
</div>
<div class="form-group">
<label for="feedback-form-title">Title</label>
<input
type="text"
class="form-control"
id="feedback-form-title"
name="title"
placeholder="Title of your feedback"
/>
</div>
<div class="form-group">
<label for="feedback-form-message">Message</label>
<textarea
type="text"
placeholder="Enter your message, then hit the submit button"
class="form-control"
name="message"
id="feedback-form-message"
rows="6"
></textarea>
</div>
<button type="submit" class="btn btn-secondary float-right">Submit</button>
</form>
And my router:
router.post(
"/",
[
check("name").trim().isLength({ min: 3 }).escape().withMessage("A name is required."),
check("email").trim().isEmail().normalizeEmail().withMessage("A valid e-mail is required."),
check("title").trim().isLength({ min: 3 }).withMessage("A valid title is required."),
check("message").trim().isLength({ min: 3 }).withMessage("A valid message is required."),
],
(request, response) => {
const errors = validationResult(request);
console.log(errors);
if (!errors.isEmpty()) {
request.session.feedback = {
errors: errors.array(),
};
return response.redirect("/feedback");
}
return response.send("Feedback form posted");
}
);
return router;
Why aren't the form values passing to the router's post method?
You need to access form fields in request.body followed by their respective name as described in THIS post.
Hi I am very new to javascript and would like to ask how to post data in server api using javascript because when I click the button it won't save and does not return any error I am folowing this code here https://github.com/devamaz/fetchAPI/blob/master/index.html here is my js code:
function postData(event){
event.preventDefault();
let bookedUser = document.getElementById('bookedUser').value;
let bookedUserName = document.getElementById('bookedUserName').value;
let bookedEmail = document.getElementById('bookedEmail').value;
let dateBooked = document.getElementById('dateBooked').value;
let startTime = document.getElementById('startTime').value;
let endTime = document.getElementById('endTime').value;
let attendeesEmail = document.getElementById('attendeesEmail[]').value;
let bookingDesc = document.getElementById('bookingDesc').value;
fetch('http://localhost:8080/api/createBooking', {
method: 'POST',
headers : new Headers(),
body: JSON.stringify({
"bookedUser": bookedUser,
"bookedUserName": bookedUserName,
"bookedEmail":bookedEmail,
"dateBooked":dateBooked,
"startTime":startTime,
"endTime":endTime,
"attendeesEmail":attendeesEmail,
"bookingDesc":bookingDesc})
}).then((res) => res.json())
.then((booking) => alert('Data Sent'))
.catch((err)=>console.log(err))
}
and here is the html:
<form id="postData">
<div>
<input type="text" placeholder="Booked User" id="bookedUser">
</div>
<div>
<input type="text" placeholder="Username" id="bookedUserName">
</div>
<div>
<input type="text" placeholder="Email" id="bookedEmail">
</div>
<div>
<input type="date" placeholder="Date Booked" id="dateBooked">
</div>
<div>
<input type="time" placeholder="Start time" id="startTime">
</div>
<div>
<input type="time" placeholder="End time" id="endTime">
</div>
<div>
<input type="text" placeholder="Attendees Email" id="attendeesEmail[]">
</div>
<div>
<textarea id="bookingDesc" cols="20" rows="5"></textarea>
</div>
<input type="submit" value="SEND POST" onclick="postData();">
</form>
I have tested the code in the backend using postman and it works fine, Thank you in advance
It is almost all right. Just add the event param in postData() function.
Actually, there is no function postData() with no params.
So, it should be:
<input type="submit" value="SEND POST" onclick="postData(event);">
I'll just post the code of the component:
class AddPostForm extends React.Component {
createPost(event) {
event.preventDefault();
let post = {
title : this.refs.title.value,
name : this.refs.name.value,
desc : this.refs.desc.value,
image : this.refs.image.value
}
this.props.addPost(post);
this.refs.postForm.reset();
}
render() {
return (
<div className="callout secondary form-area">
<h5>Add a Post to the React Blog</h5>
<form className="post-edit" ref="postForm" onSubmit={this.createPost}>
<label>Post Title
<input type="text" ref="title" placeholder="Post Title" required/>
</label>
<label>Author Name
<input type="text" ref="name" placeholder="Full Name required" required/>
</label>
<label>Post Body
<textarea
ref="desc"
placeholder="Write your post here" required/>
</label>
<label>Image URL - <span className="highlight">use this one to test 'http://bit.ly/1P9prpc'</span>
<input type="url" ref="image" placeholder="The URL of the featured image for your post" required/>
</label>
<button type="submit" className="button">Add Post</button>
</form>
</div>
)
}
}
When the function createPost is triggered, the console logs an error: Uncaught TypeError: Cannot read property 'refs' of null.
Yet when I transform the code back to ES5, it works:
var AddPostForm = React.createClass({
createPost : function(event) {
event.preventDefault();
// take the data from the form and create an object
var post = {
title : this.refs.title.value,
name : this.refs.name.value,
desc : this.refs.desc.value,
image : this.refs.image.value
}
// add the post to the App State
this.props.addPost(post);
this.refs.postForm.reset();
},
render : function() {
return (
<div className="callout secondary form-area">
<h5>Add a Post to the React Blog</h5>
<form className="post-edit" ref="postForm" onSubmit={this.createPost}>
<label>Post Title
<input type="text" ref="title" placeholder="Post Title" required/>
</label>
<label>Author Name
<input type="text" ref="name" placeholder="Full Name required" required/>
</label>
<label>Post Body
<textarea
ref="desc"
placeholder="Write your post here" required/>
</label>
<label>Image URL - <span className="highlight">use this one to test 'http://bit.ly/1P9prpc'</span>
<input type="url" ref="image" placeholder="The URL of the featured image for your post" required/>
</label>
<button type="submit" class="button">Add Post</button>
</form>
</div>
)
}
});
You should set this for createPost, because with ES2015 classes in React there is no autobinding, but this feature exists when you use React.createClass
class AddPostForm extends React.Component {
constructor(props) {
super(props);
this.createPost = this.createPost.bind(this);
}
....
}
Autobinding