I am a beginner to web development, and I am having trouble retrieving the parameters when sending a delete request to my local REST API (written using Express Js). I have already Googled the issue, but most are resolved by using body-parser.
When I return and print the req.body back to the console it comes out as:
{data: "{"Customer":"1"}"}
which seems to look correct?
But when I try and retreive
req.body.Customer;
in the routes.js file it comes out as undefined.
Am I missing something really obvious here?
JQuery function to make request
function DeleteItem(){
let data = {
Customer: $customerId.text()
}
data = JSON.stringify(data);
$.ajax({
url: "http://localhost:3000/Customers",
type: 'DELETE',
data: {
data
},
success: function(res) {
console.log(res);
BuildTable();
},
error: function(res) {
console.log(res);
alert(res);
}
});
}
Routes.js
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var appRouter = function(app) {
app.delete("/Customers", function(req, res) {
var customer = req.body.Customer;
console.log(customer);
res.send(req.body);
});
}
module.exports = appRouter;
First delete the line data = JSON.stringify(data);
then if you need the Customer you should write:
req.body.data.Customer;
or you can change your request like this:
function DeleteItem(){
let data = {
Customer: $customerId.text()
}
$.ajax({
url: "http://localhost:3000/Customers",
type: 'DELETE',
data: data,
success: function(res) {
console.log(res);
BuildTable();
},
error: function(res) {
console.log(res);
alert(res);
}
});
}
Right now you are creating a new object data and assigning the object you created before to it.
Related
I am new to node.js and I want to practice. I found this example.
I made the home page good home page but when I click any country I can't display its information, I mean I can request the data for the country I clicked but I can't send it to the page that I rendered to display these information
I want it looks like this
countryinfo
this is the node
const express = require("express")
const app = express()
const https = require("https")
var bodyParser = require('body-parser')
app.set("view engine", "ejs")
app.use(express.static("./public"))
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.get("/" , (req, res) =>{
res.sendFile(__dirname + "/index.html")
})
app.get("/:thename" , (req, res) =>{
res.render("countryinfo")
})
app.post("/:thename" , urlencodedParser,(req, res) =>{
let theName = `https://restcountries.eu/rest/v2/name/${req.params.thename}`;
https.get(`https://restcountries.eu/rest/v2/name/${req.params.thename}`, (resp) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
res.json(JSON.parse(data));
});
})
app.listen("3000")
and this is the javascript file
countries.forEach(nation=>{
nation.addEventListener("click", getInfo)
function getInfo () {
var theName = nation.children[0].getAttribute("href")
$.ajax({
type: 'GET',
url: theName,
success: function(){
}
});
$.ajax({
type: 'POST',
url: theName,
data: {name: theName},
success: function(data){//updated data
}
});
}
})
what I should do to send data to rendered page?
this how my directories looks like: directories
You may want to update your front in the success function where data has been received.
how to understand the concept of content type aplication/json, if i have restful api module, and a request on node server
var request = require('request');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
request({
url: 'http://localhost/4000/notes/12vdsgte5657',
method: 'POST',
json: {mes_id: '12vdsgte5657'}
}, function(error, response, body){
console.log(body);
});
and this on API router
module.exports = function(app, db) {
var ObjectID = require('mongodb').ObjectID;
app.get('/notes/:id', (req, res) => {
//const id = req.params.id;
console.log(req.body,id)
console.log(req.params.id,new ObjectID(id))
const details = { '_id': new ObjectID(id) };
db.collection('notes').findOne(details, (err, item) => {
if (err) {
res.send({'error':'An error has occurred'});
} else {
res.send(item);
}
});
});
}
how can i use json data to my API module, i can understand the concept if it parse parameter on body or in the url, but when in JSON i can't, what is that for what is deferent why must i use JSON, what is the concept for it
I use json: {mes_id: '12vdsgte5657'}, and I can't console it, req.param for get data from url, req.body to get data from body, from json? req.json?
what is the magic to console the json from the server, or I miss the concept
Solved
now I find the answer, you can past json like that but you required app.use(bodyParser.json());
Title says it all. I'm new to this so I'm sure it must be a simple mistake.
Here's the controller
$scope.removeProduct = function(product){
console.log(product._id);
var inData = new Object();
inData._id = product._id;
console.log(inData);
$http({ url:"/api/deleteprod/", inData, method: "POST"
}).then(function () {
console.log("got here");
var index = $scope.vehicles.indexOf(product);
$scope.vehicles.splice(index, 1);
})
};
and here's the server side.
module.exports = function(app, mongoose, config) {
app.post('/api/deleteprod', function(req, res){
console.log("in app post",req);
var MongoClient = mongodb.MongoClient;
var url='mongodb://localhost:27017/seedsdev';
});
};
Obviously what I want is to pass the _id to the server so I can work with it, but when I output req it's about 50 pages long and has none of the info I wanted. Before it's passed the object can be seen to be fine fia console.log.
What's the rookie mistake I'm making?
When calling $http, you pass the post data with a data property. Currently you're passing an inData property. Change to this:
$http({ url:"/api/deleteprod/", data: inData, method: "POST" }).then(...)
Update:
On the server side, you'll need to make sure you have a JSON parsing middleware, like that from body-parser:
app.use(require('body-parser').json())
Once you are parsing the body using body-parser, you'll have a req.body property with the parsed JSON.
What you are missing are two below things.
1) Data in post request as suggested by #Jacob
2) A parser of Post param body-parser. //npm install body-parser --save
This will help you to parse the POST data in node js.
So code would look like
$scope.removeProduct = function(product){
console.log(product._id);
var inData = new Object();
inData._id = product._id;
console.log(inData);
$http({ url:"/api/deleteprod/", data: inData, method: "POST"
}).then(function () {
console.log("got here");
var index = $scope.vehicles.indexOf(product);
$scope.vehicles.splice(index, 1);
})
};
IN Backend
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
module.exports = function(app, mongoose, config) {
app.post('/api/deleteprod', function(req, res){
console.log("in app post",req.body._id);
var MongoClient = mongodb.MongoClient;
var url='mongodb://localhost:27017/seedsdev';
});
};
the client code :
self.getjson = function () {
var timeinfo = new Object();
timeinfo.time = self.time;
timeinfo.address = self.address;
timeinfo.info = self.info;
return JSON.stringify(timeinfo);
};
alert(self.getjson());
$.ajax({
type: "POST",
//beforeSend:function(){$(".info").fadeIn('slow').html("正在提交,请稍后");},
url:'/user/add/timetemp',
data: self.getjson(),
beforeSend: function (xhr) {
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(data){
}
})
the server code app.js:
router.route('/user/add/timetemp')
.post(function(req,res){
console.log(req.body); // your JSON
res.send(req.body); // echo the result back
});
the answer from client:
enter image description here
there has data in the client.
the answer from server:
but the server is null
From the documentation:
req.body
Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser and multer.
(My emphasis.) It continues with:
The following example shows how to use body-parsing middleware to populate req.body.
var app = require('express')();
var bodyParser = require('body-parser');
var multer = require('multer'); // v1.0.5
var upload = multer(); // for parsing multipart/form-data
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.post('/profile', upload.array(), function (req, res, next) {
console.log(req.body);
res.json(req.body);
});
Side notes:
1. All of these variables on self are global variables. Global variables are a Bad Thing™. :-) Generally best to put your code in a scoping function and use locals within that scoping function.
2. new Object is almost never needed. Your getjson function can be much simpler:
self.getjson = function () {
return JSON.stringify({
time: self.time,
address: self.address,
info: self.info
});
};
or (slightly more convenient when debugging):
self.getjson = function () {
var timeinfo = {
time: self.time,
address: self.address,
info: self.info
};
return JSON.stringify(timeinfo);
};
3. There's no need for your beforeSend callback on ajax; just use the built-in contentType option:
$.ajax({
type: "POST",
//beforeSend:function(){$(".info").fadeIn('slow').html("正在提交,请稍后");},
url: '/user/add/timetemp',
data: self.getjson(),
contentType: 'application/json',
success: function(data) {
}
});
I would like NodeJS server, post.js file, to send the json object from the AJAX request to an email using only pure NodeJS.
The following is the front-end code that sends the AJAX request:
$(document).ready(function() {
$("#contact").submit(function () {
var data = {};
$.each($(this).serializeArray(), function (key, value) {
data[value.name] = value.value;
});
data.interest = [data.interest1, data.interest2, data.interest3];
delete data.interest1;
delete data.interest2;
delete data.interest3;
console.log(data);
$.ajax({
type: "POST",
data: JSON.stringify(data),
dataType: 'json',
url: "post.js",
success: function (data) {
$("#contact").addClass('success');
},
error: function () {
$("#contact").addClass('error');
}
});
return false;
});
});
Nodemailer offers a great way to have your node.js server send emails with easy setup. With this you can set up a simple node server such as:
//untested node.js code only for reference.
var express = require('express')
var app = express();
var nodemailer = require('nodemailer');
var bodyParser = require('body-parser');
app.use(bodyParser.json());
var transporter = nodemailer.createTransport('TODO: setup your SMTP');
app.post('/', function (req, res) {
var mailOptions = {
from: "TODO: sender",
to: "TODO: recipient",
text: req.body
}
app.listen('TODO: some port');
Check nodemailer's documentation for details on setting up the server to suit your needs.