Vue Js Form post issues to server - node.js

I am building a website and I cannot find a way to send my SignUp form data to my server using post. I tried with axios but it didn't work.
This is basically how my signup page looks like
<template>
<div id = "app">
<!-- <router-view /> -->
<h1>{{ $t('signup') }}</h1>
<p>{{ $t('signupMsg') }}</p>
<b-form #submit="onSubmit" #reset="onReset" method="post" >
<b-form-group
id="input-group-1"
label-for="input-1"
>
<p1> Name: </p1>
<b-form-input
id="input-1"
v-model="form.name"
required
placeholder="Enter Name and Vorname"
></b-form-input>
</b-form-group>
<b-form-group id="input-group-2" label-for="input-2" >
<p1>{{ $t('tech') }}</p1>
<b-form-input
id="input-2"
v-model="form.technicianID"
required
placeholder="Enter assigned Technician ID"
></b-form-input>
</b-form-group>
<b-form-group id="input-group-3" label-for="input-3">
<p1> Email ID: </p1>
<b-form-input
id="input-3"
v-model="form.email"
required
placeholder="Enter assigned Email ID"
></b-form-input>
</b-form-group>
<b-form-group id="input-group-4" label-for="input-4">
<p1> {{ $t('branch') }} </p1>
<b-form-input
id="input-4"
v-model="form.branch"
required
placeholder="Enter your branch"
></b-form-input>
</b-form-group>
<!-- <b-button type="submit" > <router-link to="/requestsuccess">{{ $t('signup') }}</router-link> </b-button> -->
<b-button type="submit" >{{ $t('signup') }} </b-button>
<b-button type="reset" variant="danger">{{ $t('reset') }}</b-button>
<router-link to="/" class="btn btn-link">{{ $t('back') }}</router-link>
</b-form>
</div>
</template>
<script>
import axios from 'vue-axios'
export default {
name: 'signup',
data() {
return {
form: {
name: '',
technicianID: '',
email:'',
branch: ''
}
}
},
methods: {
onSubmit(evt) {
evt.preventDefault()
axios({
method: 'post',
url: '/insert',
data: this.form
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
},
onReset(evt) {
evt.preventDefault()
// Reset our form values
this.form.name = ''
this.form.technicianID = ''
this.form.email = ''
this.form.branch = ''
// Trick to reset/clear native browser form validation state
this.show = false
this.$nextTick(() => {
this.show = true
})
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
</style>
This is how my index.js looks like for post
router.post('/insert', function(req, res, next) {
var item = {
name: req.body.name,
technicianID: req.body.technicianID,
email: req.body.email,
branch: req.body.branch
};
mongo.connect(url, function(err, db) {
assert.equal(null, err);
db.collection('users').insertOne(item, function(err, result) {
assert.equal(null, err);
console.log('Item inserted');
db.close();
});
});
res.redirect('../components/requestsuccess');
});
I am fairly new to this but I can't find a way to send my data to the server.

You can try this code below:
Backend: You can change your backend with this code below
router.post('/insert', function(req, res, next) {
console.log(req.body);
mongo.connect(url, function(err, db) {
db.collection('users').insertOne(req.body, function(err, result) {
if(err) return res.status(500).send(err);
return res.status(200).send(result.ops[0]);
db.close();
});
});
});
The code above only an example for simple case. If you want to add assert, then you can make sure it's working fine. If the simple code above it's working, then you can add assert.
Make sure you've been install cors on your server and add it in your app.js or server.js this code below:
app.use(cord({origin: "*"});
And then, make sure you call your endpoint use: http://. Not only localhost but http://localhost.
FrontEnd
onSubmit(evt) {
evt.preventDefault()
axios({
method: 'post',
url: '/insert', // make sure your endpoint is correct
data: this.form
})
.then(response => {
//handle success
console.log(response.data);
// do some stuff here: redirect or something you want
})
.catch(error => {
//handle error
console.log(error.data);
});
},
Make sure your endpoint is correct.
I hope it can help you.

Related

Next js API resolved without sending a response for /api/contact, this may result in stalled requests

Getting API resolved without sending a response for /api/contact, this may result in stalled request on the following API route in Next.js. It's using sendgrid and the email gets sent but I'm not getting a response back so I can handle errors or success message.
I've updated the below with the front end code. I'm now not getting that error but on the front end the call 'const response = await fetch('/api/contact'..' doesn't return anything
const sgMail = require('#sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_APIKEY);
export default function handler(req, res) {
if (req.method === 'POST') {
const email = {
from: process.env.EMAIL_FROM,
to: process.env.EMAIL_TO,
subject: 'Website Contact Form',
html: `<div>
<div><strong>Name:</strong> ${req.body.name}<br/></div>
<div><strong>Phone:</strong> ${req.body.phone}<br/></div>
<div><strong>Email:</strong> ${req.body.email}<br/></div>
<div><strong>more:</strong> ${req.body.more}<br/></div>
</div>`,
};
try {
return sgMail
.send(email)
.then(() => {
console.log('res1', res);
//return res;
return res.status(200).end();
})
.catch((error) => {
console.log('error', error);
return res.status(500).send(error);
});
} catch (error) {
console.log('error 2', error);
res.json(error);
return res.status(405).end();
}
}
}
import React from 'react';
import { Formik, Form } from 'formik';
import * as Yup from 'yup';
import TextAreaField from './textAreaField';
import TextField from './textfield';
function ContactForm() {
return (
<Formik
initialValues={{
name: '',
phone: '',
email: '',
more: '',
}}
validationSchema={Yup.object({
name: Yup.string().required('Required'),
phone: Yup.string().required('Required'),
email: Yup.string().email('Invalid email address').required('Required'),
more: Yup.string().required('Required'),
})}
onSubmit={async (values, { setSubmitting }) => {
setSubmitting(true);
const response = await fetch('/api/contact', {
body: JSON.stringify({
name: values.name,
phone: values.phone,
email: values.email,
more: values.more,
}),
headers: {
'Content-Type': 'application/json',
},
method: 'POST',
});
console.log('response', response);
const data = await response.json();
console.log('response 1', data);
setSubmitting(false);
}}
>
{(props) => {
const { values, setFieldValue } = props;
console.log('props', props);
console.log('values', values);
return (
<div className="c-contact-form">
<Form className="form">
<TextField label="Customer Name" name="name" type="text" placeholder="John" />
<TextField label="Phone Number" name="phone" type="text" placeholder="07909765432" />
<TextField label="Email Address" name="email" type="email" placeholder="John#gmail.com" />
<TextAreaField label="More" name="more" placeholder="More details" />
<button type="submit" className="c-btn">
Submit
</button>
</Form>
{values.success && (
<div>
<p>Your enquiry has been successfully submitted.</p>
</div>
)}
{values.nosend && (
<div>
<p>OOPS, something went wrong but we know about it. please contact us via email or phone</p>
</div>
)}
</div>
);
}}
</Formik>
);
}
export default ContactForm;
You need to send a response back like the following
try {
sgMail
.send(email)
.then(() => {
console.log('res', res.json);
return res.status(200).end();
})
.catch((error) => {
console.log('error', error);
return res.status(500).send(error);
});

AJAX broken, POST route 404 (Not Found)

I've been working on this for a couple of days. I'm certain its something really stupid, but I'm at the end of my sanity.
The public files are set up properly.
Error Message:
POST 127.0.0.1:8080/api/pvtToggle 404 (Not Found)
Front End HTML:
<li class="list-group-item list-group-item-dark">
<div class="row">
<div class="col-md-4"><strong>Heating:</strong> {{#if heating}} {{this.heating}} {{else}} N/A {{/if}}</div>
<div class="col-md-4"><strong>Cooling:</strong> {{#if cooling}} {{this.cooling}} {{else}} N/A {{/if}}</div>
<div class="col-md-4">
<input type="checkbox" id="pvt{{this.id}}" checked="{{this.private}}" onchange="togDefine({{this.id}}, {{this.private}});" data-toggle="toggle" data-on="Private" data-off="Public" data-onstyle="success" data-offstyle="danger" />
</div>
</div>
AJAX Call:
// Private-Public toggle
let togDefine = (id, pvt) => {
$.ajax({
type: "POST",
url: "/api/pvtToggle",
data: {
id: id,
newState: (pvt === 'true') ? false : true
},
success: function(text) {
if (text === 'ok') {
pvtSuccess(id, pvt);
} else {
console.log('updatePvt failed');
}
}
});
};
let pvtSuccess = (id, pvt) => {
$('#pvt' + id).attr('checked', (pvt === 'true') ? 'false' : 'true');
};
Back End:
//TOGGLE Private vs Public PROPERTY
app.put('/api/pvtToggle/', isAuthenticated, function(request, response) {
db.Prop.update({
private: request.params.newState
}, {
where: {
id: request.params.id
}
}).then(data => {
response.send('ok');
}).catch(error => {
console.log(error);
});
});
Please help me figure out why the request isn't working properly. :D
Your endpoint is app.put, implying it responds to a PUT request,
but your ajax/fetches are making POST requests.

NodeJS render html file with form not working on angular side

I am using ExpressJS with EJS template view engine. I am trying to show an HTML file on the angular component, but the form tag and its child input tag do not work on the angular side. They show only label data.
On NodeJS
agreementController.js
exports.getAgreementHtml = async (request, response, next) => {
const params = request.query
let reqPath = path.join(__dirname, '../agreements');
var agreementObj = {
user: { email: "example#gmail.com" }
}
// render domestic rent html
ejs.renderFile(reqPath + '/domestic_rent.ejs', agreementObj, {}, function (err, str) {
if (err !== null) {
responseObj.status = errorCodes.DATA_NOT_FOUND
responseObj.message = language.getMessage('NO_RECORD_FOUND')
response.send(responseObj)
return
}
responseObj.status = errorCodes.OK
responseObj.data = str
response.send(responseObj);
return;
});
}
domestic_rent.js
<form>
<div class="form-group">
<p><%= user.email %></p>
<div class="col-sm-offset-2 col-sm-10">
<input type="text" class="form-control" id="inputEmail3" placeholder="test" required name="test">
</div>
</div>
</form>
On Angular 8 Side
agreement-show.component.ts
getAgreementData() {
const params = {
id: this.agreementId
};
this.agreementService.getAgreementHtml(params).subscribe(
(result) => {
console.log('result agreement data::: ', result);
if (result.status !== 200) {
this.commonService.change.emit({ status: 'error', message: 'unknown error' });
return;
}
this.someHtml = result.data;
return;
}, (error) => {
console.log('error', error)
this.commonService.change.emit({ status: 'error', message: error.message });
}
);
}
agreement-show.component.html
<div [innerHTML]="someHtml"></div>
Output Attachment
By using ElementRef function we can add html runtime.
Please use following step:
#ViewChild('showitems') showitems: ElementRef;
const elemt: HTMLElement = this.showitems.nativeElement;
this.someHtml = result.data;
elemt.innerHTML = this.someHtml;

Basic post request for users using express (React)

I am having serious issues trying to solve this issue and any help would be appreciated greatly
So all I am trying to do is a simple register activity for users where I will be able to sign them up to the site.
I am using mssql, and express.
This is My Register.js. All I want is for the details input into the buttons to be passed through to the json body so it can then be used in my server.js.
Register.js
class AddUsers extends React.Component {
constructor() {
super();
this.state = { users: [] };
this.onSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
const data = { email: this.ref.email, password: this.ref.password };
// const data = { name: "", password: "" };
fetch("/admin-Add-Users", {
method: "POST", // or 'PUT'
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => {
console.log("Success:", data);
})
.catch(error => {
console.error("Error:", error);
});
}
render() {
console.log(this.state.users);
return (
<div>
<LoginForm></LoginForm>
<form onSubmit={this.onSubmit}>
<input type="text" placeholder="email" ref="email" />
<input type="text" placeholder="password" ref="password" />
<input type="submit" />
</form>
</div>
);
}
}
This is my server.js (config file is working). Here all I want is for the data previously added to be stored in my database (SQL server).
app.post("/admin-Add-Users", function(req, res) {
const { password, email } = req.body;
var request = new sql.Request();
// query to the database and get the records
request.query( "insert into Login (email, password) values ('"+email+"','"+password+"')", function(err, recordset) {
if (err) console.log(err);
});
res.send({ message: "Success" });
});
I have no idea how to get the data from the inputs to just be stored through my server.js. Please any help or examples are appreciated. I am new to react so please explain like I am five years old.
Error I am now receiving
Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the method `isPropagationStopped` on a released/nullified synthetic event. This is a no-op function. If you must keep the original synthetic event around, use event.persist().
You should try to avoid use refs in react unless you have a good reason to use them (some things like animations need to be controlled imperatively).
The React way is to do things declaratively with state, so changing an input updates the associated state field, and then the onSubmit function takes the values from state. Something like this:
class AddUsers extends React.Component {
constructor() {
super();
this.state = { users: [], email: '', password: '' };
this.onSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
const data = { email: this.state.email, password: this.state.password };
fetch("/admin-Add-Users", {
method: "POST", // or 'PUT'
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => {
console.log("Success:", data);
})
.catch(error => {
console.error("Error:", error);
});
}
render() {
console.log(this.state.users);
return (
<div>
<LoginForm></LoginForm>
<form>
<input type="text" placeholder="email" value={this.state.email} onChange={e =>
this.setState({email: e.target.value})} />
<input type="text" placeholder="password" value={this.state.password} onChange={e =>
this.setState({password: e.target.value})} />
<input type="submit" onPress={this.onSubmit} />
</form>
</div>
);
}
}

NodeJS - AJAX POST 404 (Not Found)

I am trying to send values from one file to another on click of items displayed.
While doing so, I am getting the error:
POST http://localhost:4000/todo/addToCart 404 (Not Found) jquery-3.3.1.js:9600
My app.js file:
//More codes above to set-up express and all
app.use(express.static('./public'));
todoController(app); //give todocontroller the reference to express
app.listen(4000); //listen on a port
console.log('server is running');
Controller:
module.exports = function(app) {
app.get('/todo', function(req, resp) {
Todo.find({}, function(err, data) {
if (err) throw err;
console.log('get method');
resp.render('todo', {
todos: data
});
});
});
//Few More Code
app.post('/todo', urlencodedParser, function(req, resp) {
console.log('post method');
resp.render('addToCart', {
data: req.body
});
});
};
Model for data interaction:
$('li').on('click', function() { //when user clicks on an item in the list
var item = $(this).text().replace(/ /g, "-"); //traps the item user clicked on
alert(item);
$.ajax({
type: 'POST',
url: '/todo/addToCart', //+item append that item to the url
success: function(item) {
location.reload(); //refresh the page
}
});
});
Parent ejs:
<div id="todo-table">
<form id="todoForm" method="post" action="/todo">
<input type="text" name="item" placeholder="Add new Item..." required />
<button type="submit">Add Item</button>
<ul>
<% for (var i=0;i<todos.length; i++){ %>
<li>
<%=todos[i].item%>
</li>
<% } %>
</ul>
</form>
</div>
Child ejs(to which I need to re-direct):
<div id="itemSelect">Selected Item:
<form id="addToCart" method="post" action="/addToCart">
<button type="submit" id="btnCheckOut">Check out</button>
<%=data.item%>
</form>
</div>
Please help. I am new, kindly point out my mistake.
Many thanks.
The route you created on your nodejs server here:
app.post('/todo', urlencodedParser, function (req, resp) {
console.log('post method');
resp.render('addToCart', { data: req.body });
});
Matches all the POST requests made to the /todo endpoint, not the /todo/addToCart which doesnt exist. This is why you obtain a 404.
Your ajax request should be like so:
$('li').on('click', function () {
var item = $(this).text().replace(/ /g, "-");
alert(item);
$.ajax({
type: 'POST',
url: '/todo', // 'addToCart' has been removed from the path
success: function (item) {
location.reload();
}
});
});

Resources