I am making a post request to insert comments into my MongoDB database. I am receiving an error 500 when trying to make this insert. I believe this is due to the value not being received when making the request. Where am I going wrong when posting these values?
app.post('/addComment', (req, res) =>{
console.log(req.body.description, typeof(req.body.description));
var com = new Comment({
description: req.body.description,
sentiment: ml.classify(req.body.description),
status: req.body.status,
});
com.save(function(err, insComment){
if(err){
console.log('Error loading data');
}
else{
res.send(insComment);
}
});
});
Controllers.js
exports.CommentController = function($scope, $http){
$scope.addComment = function(){
$http({
method :'POST',
url: '/addComment',
headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'},
data:{
//username:$scope.username,
description: $scope.description,
//sentiment: $scope.sentiment,
status:$scope.status,
}
}).then(function (response){
$scope.user = response;
console.log('DESCRIPTION ' + typeof($scope.description))
//$scope.user = response;
}, function(err){
console.log(err);
})
}
}
$scope.addComment = function(){
$http.post('/addComment', {
description: $scope.review.description,
status: $scope.review.status,
},
{headers: {'Content-Type': 'application/json'}}).
success(function(data){
$scope.user = data;
console.log('DESCRIPTION 2 ' + typeof($scope.description))
console.log(data);
}).error(function(err){
console.log(err);
});
};
Front end
<div class="row p-b-25">
<div class="col-12 p-b-5">
<input type="text"
ng-model="review.description">
</div>
<add-comment></add-comment>
</div>
Please add complete url and try.
e:g
$http({
method :'POST',
url: 'http://localhost:3000/addComment',
Related
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.
I'm trying to achieved the following:
Client has to fill a form and submit it to the node server
If client has a business card, snap a picture and it updates the form.
I have the API to translate image to json.
But I struggle to upload that image through node.
I created an html form with an input=file.
When input is changed, Ajax is called to upload that image.
On node, the request is received and basically transferred to that other website (camcard).
Json response should be sent back to client.
I just can't achieve that..
Any idea?
Here is some code. I do a post in 2 ways (regular and Ajax)
Html client:
<form method='POST' id="formCard"
enctype='multipart/form-data'>
<input type=file class="btn btn-outline-primary" name=upfile
size=20 id="cardSelector" onChange="changeFile()">
</form>
<form method='POST' action='/postCardPic'>
Please specify a JPG file<br>
<input type=file name=upfile size=20><br><br>
<input type=submit value='Upload'>
</form>
<script>
function changeFile() {
var formData = new FormData();
formData.append( 'file', $( '#cardSelector' )[0].files[0] );
$.ajax({
data: formData,
enctype: 'multipart/form-data',
processData: false,
contentType: false,
type: "POST",
url: "/postCardPic",
success: function (response) { // on success..
console.log(response); // update the DIV
},
complete: function (data) {
hideLoader();
}
});
}
</script>
On the server side:
App.use(bodyParser.urlencoded({
extended: false,
limit: '50mb',
parameterLimit:'50000'
}));
app.use(bodyParser.json({
extended: false,
limit: '50mb',
parameterLimit:'50000'
}));
app.post('/postCardPic', function(req, response) {
var urlCamCard='http://whatever.com'
// var form = new Form();
// form.parse(req, function(err, fields, files) {
// res.writeHead(200, {'content-type': 'text/plain'});
// res.write('received upload:\n\n');
// res.end(util.inspect({fields: fields, files: files}));
// });
// form.on('file', function(name,file) {
// //stream it to localhost:4000 with same name
// fs.createReadStream(file.path).pipe(request.post(urlCamCard))
// });
request.post({
url:urlCamCard, form:req.body}, function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log('Upload successful! Server responded with:', body);
});
response.end();
});
Log in both cases is the same:
Upload successful! Server responded with: ErrorCode: -1 ErrorMsg: Image data size not supported
I found the solution.
Here's is the code on the server side:
App.post("/postCardPic", function(req, res) {
try {
var form = new multiparty.Form();
form.parse(req, function(err, fields, files) {});
form.on("file", function(name, file) {
var formData = {
file: {
value: fs.createReadStream(file.path),
options: {
filename: file.originalFilename
}
}
};
request.post(
{
url: theurl,
formData: formData
},
function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error("upload failed:", err);
}
res.end(body);
}
);
});
} catch (err) {
console, log(err);
res.end();
}
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();
}
});
});
I would like to update my view after an ajax call, rendering compiled ejs from the server.
These two previous questions seem to achieve this but I cannot update my view
Can't Render EJS Template on Client
How to generate content on ejs with jquery after ajax call to express server
So from what I understand I should compile my ejs file (partial) on the server.
fixtures.ejs
<% fixtures.forEach((fixture) => { %>
<h2><%= fixture.home_team %> vs <%= fixture.away_team %></h2>
<% }) %>
index.js
app.post('/league_fixtures', async function (req, res) {
try {
var league_name = req.body.league_name;
const fixtures = await leagueFixtures(league_name);
//compile view
fs.readFile('./views/fixtures.ejs', "utf-8", function(err, template) {
fixture_template = ejs.compile(template, { client: true });
var html = fixture_template({fixtures: fixtures});
console.log(html);
// This logs out my HTML with fixtures so I am almost there
// <h2>Club Africain vs Al-Faisaly Amman</h2>
// <h2>Al Nejmeh vs ASAC Concorde</h2>
});
res.json({fixtures: fixtures });
} catch (err) {
res.status(500).send({ error: 'Something failed!' })
}
});
Ajax
$("a.league-name").on("click", function (e) {
e.preventDefault();
var league_name = $(this).text().trim();
$.ajax({
url: '/league_fixtures',
type: 'POST',
dataType: "json",
data: { league_name: league_name },
success: function(fixtures){
// How do i get HTML from server into here ?
$('#panel_' + league_name).html(fixtures);
},
error: function(jqXHR, textStatus, err){
alert('text status '+textStatus+', err '+err)
}
})
});
});
I don't get any errors when I fire the ajax request but I also do not get any data or HTML updated in my div.
What am I doing wrong?
So I finally got a working solution:
index.js
app.post('/league_fixtures', async function (req, res) {
try {
const league_name = req.body.league_name;
const fixtures = await leagueFixtures(league_name);
const file = await readFile('./views/fixtures.ejs');
var fixture_template = ejs.compile(file, { client: true });
const html = fixture_template({fixtures: fixtures});
res.send({ html: html });
} catch (err) {
res.status(500).send({ error: 'Something failed!' })
}
});
ajax call
$.ajax({
url: '/league_fixtures',
type: 'POST',
dataType: "json",
cache: true,
data: { league_name: league_name },
success: function(fixtures){
var html = fixtures['html'];
$('#panel_' + league_name).html(html);
},
error: function(jqXHR, textStatus, err){
alert('text status '+textStatus+', err '+err)
}
})
I'm having trouble with getting the proper data out of req.body
When I fetch a request to the server I get this in my console (Ex: 'Wash dishes' as the value for the input)
// console log
{}
{ item: 'Wash dishes' }
an empty object first and then the item I specified.
html file
<form autocomplete="off" id="formform" method="POST">
<input type="text" name="item" placeholder="Add new item..." required id="inputinput" >
<button type="submit">Add Item</button>
</form>
test-w-fetch.js
let newForm = document.getElementById('formform');
newForm.addEventListener('submit', (evt) =>{
let item = document.getElementById('inputinput');
let todo = {item: item.value};
fetch('/todo', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: todo
}).then( (response) => {
return response.json();
}).then((data) =>{
location.reload();
}).catch((err) =>{
console.log(`There's an ${err}!!`);
});
return false;
});
Here's my POST route on the server
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.post('/todo', (req, res) => {
// Need to get data from the view and add it to mongodb
console.log(req.body);
let newItem = new Todo(req.body);
newItem.save( (err, data) =>{
if (err) throw err;
res.json(data);
});
});
Other option I have tried was taking error checking req.body.item property, storing it into a new object, and passing it to the database, but the empty object is still going through the body and getting saved to the database
One thing you could try to is use Postman to te to see if the issue is server or client side. Would help narrow down the troubleshooting surface area.