JSON data not defined - javascript

I tried to make a food recipe app and wrote this code using node:
const express = require("express");
const bodyParser = require("body-parser");
const https = require("https");
const app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.get("/", function(req, res) {
res.sendFile(__dirname + "/index.html");
});
app.post("/", function(req, res) {
const numberOfRecipes = req.body.totalRecipes;
const apiKey = "apiKey...";
const url = "https://api.spoonacular.com/recipes/random?apiKey=" + apiKey + "&number=" + numberOfRecipes;
https.get(url, function(response) {
response.on("data", function(data) {
const recipeData = JSON.parse(data);
// console.log(recipeData);
// console.log(data);
const title = recipes[0].title;
res.write("<h1>The title of the recipe is " + title + ".</h1>");
res.send();
})
});
});
app.listen(3000, function() {
console.log("The server started at port 3000");
});
But the terminal says
C:\Users\ArunBohra\Desktop\food-recipes\app.js:23
const recipeData = JSON.parse(data);
^
ReferenceError: data is not defined
at ClientRequest. (C:\Users\ArunBohra\Desktop\food-recipes\app.js:23:41)
Can anyone help me with this?

I think your not accessing that API content right. Try this :
axios.get('https://api.github.com/users/mapbox')
.then((response) => {
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
});
find a popular third-party library like Axios or others and use that to make API calls. then do console logs that will you
refer this one How do I use axios within ExpressJS?
and this one ReferenceError: request is not defined

Related

fetch() POST requests with Express: unexpected end of JSON input

I've been trying to practice with some HTTP requests, and specifically I want to send a POST request, with data taken from an field, and sent via fetch() to a url on my localhost thats set up with express. From there i want to somehow get the response back and have that be displayed on my HTML doc.
However, I've ran into a real head scratcher when it comes to getting response.json() to be anything other than undefined.
here's my frontend script:
const url = "/result";
const inputField = document.querySelector("#write");
const submitButton = document.querySelector("#submit");
const responseField = document.querySelector("#text-goes-here");
const postText = async () => {
const text = inputField.value;
const data = JSON.stringify({ destination: text });
try {
const response = await fetch(url, {
method: "POST",
body: data,
headers: {
"Content-type": "application/json",
},
});
if (response.ok === true) {
const jsonResponse = await response.json();
responseField.innerHTML = jsonResponse;
}
} catch (error) {
console.log(error);
}
};
const displayText = (event) => {
event.preventDefault();
while (responseField.firstChild) {
responseField.removeChild(responseField.firstChild);
}
postText();
};
submitButton.addEventListener("click", displayText);
and my server script:
const express = require("express");
const bodyParser = require("body-parser");
const read = require('fs');
const router = express.Router();
const app = express();
const port = 3000;
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get("/", (req, res) => {
res.sendFile("public/index.html");
})
router.post("/result", (req, res) => {
console.log(req.body);
res.send();
});
app.use("/", router);
app.listen(port, () => {
console.log(`Server running at port: ${port}`)
});
I did some digging in the dev console and found that (response.ok) is in fact "true", yet it errors out into the catch statement saying "SyntaxError: Unexpected end of JSON input
at postText (script.js:23)"
which is this line exactly:
const jsonResponse = await response.json();
can anyone shed any light on what i'm doing wrong here? I'm at a loss at this point
This error means that you're trying to parse something that is not a valid JSON object.
"SyntaxError: Unexpected end of JSON input at postText (script.js:23)"
Which is true, because the response you're sending back to the frontend is not a JSON.
router.post("/result", (req, res) => {
console.log(req.body);
// The response is not a valid JSON object
res.send();
});
You can change res.send() to res.json() and give it a valid object.
res.json({ name:"John", age:30, car:null })

How to fix Type Error cannot read property 'cityName' of undefined in the weather forecast project?

I had seen every syntax but I could see any type of error in my project. Can you help me where is the problem really is?
I wanted to make a weather project by the api but when I load the code in the browser it is showing the type error "cityName" but I don't see any error in there.can you help me out where is the problem is I give a pic also.
HTML file
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Weather Forcast</title>
</head>
<body>
<form action="/" method="post">
<label for="cityInput">City Name:</label>
<input id="cityInput" type="text" name="cityName">
<button type="submit">Go</button>
</form>
</body>
</html>
JavaScript file
const express= require("express");
const https = require("https");
const app = express();
app.get("/", function(req, res){
res.sendFile(__dirname + "/index.html");
});
app.post("/", function(req, res){
const query =req.body.cityName;
const apiKey ="e3e24d2fb12aafc8d8bf05b91d5f0ae0";
const unit ="metric";
const url ="https://api.openweathermap.org/data/2.5/weather?q=" + query + "&appid=" + apiKey + "&units=" + unit;
https.get(url, function(response){
console.log(response.statusCode);
response.on("data", function(data){
const weatherData = JSON.parse(data)
const temp = weatherData.main.temp
const weatherDescription = weatherData.weather[0].description
res.write("<p>The weather is currently" + weatherDescription + "</p>");
res.write("<h1>The tempreature in "+ query +" is " + temp +"degress Celcius.</h1>")
res.send();
})
})
});
app.listen(3000, function(){
console.log("Server is running on Port 3000");
})
The error I got from the browser
you have not installed body-parser which parse the incoming request and you are using req.body.cityName which javascript would not understand.
So, refer this link body-parser
and refer to the following code.
//jsonhint express versio:6.0
const express= require("express");
const https = require("https");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({
extended: false
}));
app.get("/", function(req, res){
res.sendFile(__dirname + "/index.html");
});
app.post("/", function(req, res){
const query =req.body.cityName;
const apiKey ="e3e24d2fb12aafc8d8bf05b91d5f0ae0";
const unit ="metric";
const url ="https://api.openweathermap.org/data/2.5/weather?q=" + query + "&appid=" + apiKey + "&units=" + unit;
https.get(url, function(response){
console.log(response.statusCode);
response.on("data", function(data){
const weatherData = JSON.parse(data)
const temp = weatherData.main.temp
const weatherDescription = weatherData.weather[0].description
res.write("<p>The weather is currently" + weatherDescription + "</p>");
res.write("<h1>The tempreature in "+ query +" is " + temp +"degress Celcius.</h1>")
res.send();
})
})
});
app.listen(3000, function(){
console.log("Server is running on Port 3000");
})
Look like you haven't use bodyParser yet, so req.body will be undefined.
Try add bodyParser to your JavaScript file to see if it work
const express= require("express");
const https = require("https");
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
You have to parse the request body before performing any kind of operation. You can use express.json() middleware function to parse the request body. For more information visit Express Official Documentaion
app.use(express.json());
Final code:
const express= require("express");
const https = require("https");
const app = express();
// Middleware function to parse the request body;
app.use(express.json());
app.get("/", function(req, res){
res.sendFile(__dirname + "/index.html");
});
app.post("/", function(req, res){
const query =req.body.cityName;
const apiKey ="e3e24d2fb12aafc8d8bf05b91d5f0ae0";
const unit ="metric";
const url ="https://api.openweathermap.org/data/2.5/weather?q=" + query + "&appid=" + apiKey + "&units=" + unit;
https.get(url, function(response){
console.log(response.statusCode);
response.on("data", function(data){
const weatherData = JSON.parse(data)
const temp = weatherData.main.temp
const weatherDescription = weatherData.weather[0].description
res.write("<p>The weather is currently" + weatherDescription + "</p>");
res.write("<h1>The tempreature in "+ query +" is " + temp +"degress Celcius.</h1>")
res.send();
})
})
});
app.listen(3000, function(){
console.log("Server is running on Port 3000");
})

getting error undefined 176 while trying to access API for covid data

I tried JSON.parse(data) but I get:
"error undefined at Lat : 54".
This is the value from my string. I tried stringify, toString but I am getting hexadecimal, binary but no data.
Here is my code which I am running:
const express = require("express");
const https = require("https");
const app = express();
const url = "https://api.covid19api.com/live/country/india/status/confirmed";
app.get("/", function(req, res) {
https.get(url, function(response) {
console.log(response.statusCode)
response.on("data", function(data) {
const strCovid = JSON.parse(data);
const cases = (strCovid.Confirmed);
console.log(cases);
res.send("hi" + cases);
});
});
});
app.listen(3000, function() {
console.log("server at 3000")
});

How do I send image data from a url using express?

I want my the /image of my app to return a random image, how can I do that?
app.js:
const app = express();
app.get('/image', async (req, res) => {
const url = 'https://example.com/images/test.jpg';
res.send(/**/); // How do I send the image binary data from the url?
});
index.html
In HTML, this image actually shows the content of the image https://example.com/images/test.jpg
<img src="https://my-app.com/image" />
We have the same problem, and this is my solution for this using request package, so you have to yarn add request or npm i request first.
your code should be like this
const request = require('request');
const express = require('express');
const app = express();
app.get('/image', async (req, res) => {
const url = 'https://example.com/images/test.jpg';
request({
url: url,
encoding: null
},
(err, resp, buffer) => {
if (!err && resp.statusCode === 200){
res.set("Content-Type", "image/jpeg");
res.send(resp.body);
}
});
});
There is res.sendFile in Express API
app.get('/image', function (req, res) {
// res.sendFile(filepath);
});
const express = require("express");
const https = require("node:https");
const app = express();
const port = 3000
app.get("/", function(req, res){
const url = "https://api.openweathermap.org/data/2.5/weather?q=Paris&units=metric&appid=65441206f989bc53319e2689fccdc638";
https.get(url, function(response){
response.on("data", function(data){
const weatherData = JSON.parse(data)
const icon = weatherData.weather[0].icon
const imageUrl = "http://openweathermap.org/img/wn/" + icon + "#2x.png"
res.write("<img src=" + imageUrl + " ></img>")
res.send();
})
});
})
You can save all such image links in json or any of your choice data file and get from them randomly and forward and pass them through variable in response. Like: res.send(imgURL: 'https://example.com/images/test.jpg'); or you can pass url variable in init.

Returning String with Express post

I have this app.js file:
let express = require('express')
let app = express()
let Clarifai = require('clarifai')
app.use(express.urlencoded({extended: true}))
app.use(express.static('./public'))
let link = app.post('/route', (req, res) => {
let linkString = req.body.link
res.send(JSON.stringify(linkString))
})
app.listen(3000)
const capp = new Clarifai.App({
apiKey: 'MyAPIKeyIsHere'
});
predict = capp.models.initModel({id: Clarifai.FOOD_MODEL, version: "aa7f35c01e0642fda5cf400f543e7c40"})
.then(generalModel => {
return generalModel.predict(link)
})
.then(response => {
var concepts = response['outputs'][0]['data']['concepts']
console.log(concepts)
})
console.log('Express app running on port 3000')
console.log(link)
I am trying to return a string from the app.post method but it returns a JSON file. How should I do it exactly?
You can explicitly set the content type to text/html, before sending the data.
res.set('Content-Type', 'text/html');
res.send(JSON.stringify(linkString));
Are you sure that req.body.link is a string? If yes you could just pass linkString variable in send:
let link = app.post('/route', (req, res) => {
let linkString = req.body.link
res.send(linkString)
})

Categories

Resources