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.
Related
I start learning Node.js and Express.js and I'm trying to create a simple API to list data from JSON file (using the GET method) and add a new user using the POST method.
the GET method works fine but the POST method does not work
when I request http://127.0.0.1:8080/listusers the API sends all users in a JSON file.
when I request http://127.0.0.1:8080/adduser the API has to add new User Info and send the new data back to the browser.
NOTE: I read all the questions on Stackoverflow about this problem but
non of them help me so I have to ask again.
the problem is when I request http://127.0.0.1:8080/adduser I get the following error
Cannot GET /adduser
here is the server.js:
var express = require('express');
var app = express();
var fs = require('fs');
var user = {
"user4" : {
"name" : "mounir",
"password" : "password4",
"profession" : "teacher",
"id": 4
}
};
app.post('/adduser', function (req, res) {
// First read existing users.
fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
data = JSON.parse( data );
data["user4"] = user["user4"];
console.log( data );
res.end(JSON.stringify(data) );
});
});
app.get('/listusers', function (req, res) {
fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
console.log(data);
res.end(data);
});
});
var server = app.listen(8080, function () {
var host = server.address().address;
var port = server.address().port;
console.log("listening at http://%s:%s", "0.0.0.0", port)
});
The answer is in the error. Cannot GET /adduser. Keyword GET! If you are making a post request, be sure you include the appropriate headers and that you are making a POST request, with a body, and not a GET request. For instance if you are using fetch:
const myInit = {
method: 'POST',
headers: myHeaders,
body: {
...
}
};
fetch("http://127.0.0.1:8080/adduser", myInit)
.then(res => {
...
});
i had a proplem with making two js files one to be put in 'website' directory and the other outside it and when i add a post request it adds a new item to the array from the server side js file and itried it alot and it didnt work so ..
thats My ServerSide Code
/* Empty JS object to act as endpoint for all routes */
projectData = {};
/* Express to run server and routes */
const express = require('express');
/* Start up an instance of app */
const app = express();
/* Dependencies */
const bodyParser = require('body-parser')
/* Middleware*/
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const cors = require('cors');
app.use(cors());
/* Initialize the main project folder*/
app.use(express.static('website'));
const port = 3000;
/* Spin up the server*/
const server = app.listen(port, listening);
function listening(){
// console.log(server);
console.log(`running on localhost: ${port}`);
};
// GET route
app.post('/add', function (req, res) {
let data = req.body;
console.log(data);
});
// POST an animal
const data = []
app.post('/animal', addAnimal)
function addAnimal (req,res){
data.push(req.body);
console.log(data);
}
and That Is My ClientSide Code
/* Function to POST data */
const postData = async ( url = '', data = {})=>{
console.log(data)
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data), // body data type must match "Content-Type" header
});
try {
const newData = await response.json();
console.log(newData);
return newData
}catch(error) {
console.log("error", error);
// appropriately handle the error
}
}
// TODO-Call Function
postData('/addAnimal', {animal:'Tiger'});
postData('/addAnimal', {animal:'Lion'});
when i run the code inside the vs code editor it displays "{ animal: 'lion' }
{ animal: 'Tiger' }"
But it never console log the data
you forget to send the respone
must the route callback have a res endpoint
function addAnimal (req,res){
data.push(req.body);
console.log(data);
// add res end point
res.json({msg : 'added'})
}
//here too
app.post('/add', function (req, res) {
let data = req.body;
console.log(data);
res.end('hello world')
});
Your route is /add or /animal not /addAnimal
postData('/add', {animal:'Tiger'});
in your ServerSide this function should display a log
app.post('/add', function (req, res) {
let data = req.body;
console.log(data);
});
You can't console.log the data in your try / catch because you don't return any response in your server side. But first try log data in your server side controller for confirm the good serverSide execution, and return your response.
I am trying to make a newsLetter service using NodeJS & Express by using mailchimp API on hyper shell. I have installed all necessary things including npm,express,request,https module. The code works fine untill when i try to write the user Information in the mailChimp server and showing me the typeError message: request.write() is not a function. Below is my code & the snap of my errorCode.
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const request = require("request");
const https = require("https");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
app.get("/", function (req, res) {
res.sendFile(__dirname + "/signup.html");
});
app.post("/", function (req, res) {
const firstName = req.body.fname;
const lastName = req.body.lname;
const email = req.body.email;
const password = req.body.pass;
const cPassword = req.body.cPass;
//console.log(firstName);
//res.send(firstName);
var data = {
members: [
{
email_address: email,
status: "subscribed",
merge_fields: {
FNAME: firstName,
LNAME: lastName
}
}
]
};
const jsonData = JSON.stringify(data);
const url = "https://us1.api.mailchimp.com/3.0/lists/97d15bb1ff";
const options = {
method: "POST",
auth: "Mr.M:d2f2f965b9e6b751a305bb6ce2ad7ed4-us1",
};
https.request(url, options, function (response) {
response.on("data", function (data) {
console.log(JSON.parse(data));
});
});
request.write(jsonData);
request.end();
//res.send("hey")
});
app.listen(3000, function () {
console.log("Server is running at port 3000");
});
Error Message Picture
res.write(jsonData)
res.end()
use above code instead of request.write(jsonData), request.end().
https.request(url, options, function (response) {
response.on("data", function (data) {
console.log(JSON.parse(data));
}); });
instead use this:
const request = https.request(url, options, function (response) {
response.on("data", function (data) {
console.log(JSON.parse(data));
});
});
As already specified by Lingyu Kong, you need to save your request in a constant variable that will allow you to call upon it later:
The node.js website link below illustrates this perfectly:
https://nodejs.org/api/http.html#http_http_request_url_options_callback
You should have saved the ClientRequest into a variable called request, and after that, you could do the write and end.
Like that :
const request = https.request(url, options, function (response) {
response.on("data", function (data) {
console.log(JSON.parse(data));
});
You forgot to put in
const request = https.request(url, options, function(response) {
response.on("data", function(data) {
console.log(JSON.parse(data));
replace the code below:
https.request(url, options, function(response)
with this code:
const request = https.request(url, options, function(response)
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.
I want to render to the ui / print to console log some object value from GET response.
I'm using Node JS for my server side and HTML + JS for my client side.
Because my goal is to render data and the request type is cross domain I can't use "fetch" function.
My only alternative to execute it is to send it by "JSONP" dataType.
Actually, the request is sent and the response receives by callback as well, but my code is print "null" to the console and not the response data.
When I've tried to used JSON.parse() it received a "parseerror".
The expected result it's to get only the image tag value (2.0.90) and to print this inside the console log / render it to the UI.
async function uiChecking() {
let index;
const hostsDock = [qa + dockers];
let lengthVal = hostsDock.length;
for (let hostIndxD = 0; hostIndxD < lengthVal; hostIndxD++) {
index = hostIndxD;
let url = hostsDock[hostIndxD];
$.ajax({
url: url,
dataType: 'jsonp',
}).done( function(data) {
console.log("A " + data);
});
}
}
**Server.js **
var express = require('express');
var cors = require('cors');
var app = express();
var path = require("path");
var fetch = require('fetch-cookie')(require('node-fetch'));
var btoa = require('btoa');
var http = require('http');
var corsOptionsDelegate = function (req, callback) {
var corsOptions;
if (whitelist.indexOf(req.header('Origin')) !== -1) {
corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response
}else{
corsOptions = { origin: false } // disable CORS for this request
}
callback(null, data , corsOptions) // callback expects two parameters: error and options
};
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/view');
app.set('view engine', 'html');
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res){
res.render('index');
res.render('logo');
res.writeHead(200, {'Content-Type': 'application/json'});
});
// app.get('/products/:id', cors(corsOptionsDelegate), function (req, res, next) {
// res.json({msg: 'This is CORS-enabled for a whitelisted domain.'})
// });
app.get('/data/:id', function (req, res, next) {
var opts = {
host: config.alertService.host,
port: config.alertService.port,
method: 'GET',
path: '/DataService/rest/receiveData/' + req.params.id
}
var reqGet = http.request(opts, function (dataResponse) {
var responseString = '';
dataResponse.on('data', function (data) {
responseString += data;
});
var response = {x:[],y:[],z:[],t:[]};
dataResponse.on('end', function () {
var responseObject = JSON.parse(responseString);
var accs = responseObject.data.listPCS;
for(var i in accs){
response.x.push(accs[i].accX);
response.z.push(accs[i].accY);
response.y.push(accs[i].accZ);
response.t.push(accs[i].timestamp);
}
res.jsonp(response);
});
});
reqGet.end();
reqGet.on('error', function (e) {
console.error(e);
});
});
if (app.settings.env === 'production') {
app.error(function(err, req, res) {
res.render('new404.html', {
status: 500,
locals: {
error: error
}
});
});
}
app.listen(8033, function () {
console.log('CORS-enabled web server listening on port 8033')
});
You need to iterate through the response to return the result e.g..
$.each(data, function(index) {
console.log(data[index].ui);
console.log(data[index].id); console.log(data[index].Name);
});