"cannot read data property error" when rendering ejs with axios - javascript

I'm getting "TypeError: Cannot read property 'data' of undefined" when i try to render results.ejs with data from api. Can anyone show what's wrong with render code? Thanks.
index.js:
const axios = require("axios");
const express = require("express");
const app = express();
var link = "http://www.omdbapi.com/?apikey=thewdb&";
var title = "hababam sinifi";
var year = "";
var plot = "";
app.set("view engine", "ejs");
app.use(express.static("public"));
app.get("/", (req, res) => {
res.render("home.ejs");
});
app.get("/results", (req, res) => {
res.render("results.ejs");
});
axios.get(`${link}t=${title}&y=${year}&plot=${plot}`)
.then((req, res) => {
// handle success
const data = res.data;
res.render("results.ejs", { data: data });
})
.catch((err) => {
// handle error
console.log(err);
})
.then(() => {
// always executed
});
app.listen(3000, () => console.log("Server started at http://localhost:3000"));
results.ejs:
<%- include("partials/header.ejs"); %>
<h1>Results</h1>
<%= data %>
<%- include("partials/footer.ejs"); %>

As #blex stated in the comments you API call should be inside the route callback, axios call returns an object with the data property.
Inside the route callback you have access to req and res parameters.
const axios = require("axios");
const express = require("express");
const app = express();
var link = "http://www.omdbapi.com/?apikey=thewdb&";
var title = "hababam sinifi";
var year = "";
var plot = "";
app.set("view engine", "ejs");
app.use(express.static("public"));
app.get("/", (req, res) => {
res.render("home.ejs");
});
app.get("/results", (req, res) => {
axios.get(`${link}t=${title}&y=${year}&plot=${plot}`)
.then((apiResponse) => {
// handle success
const data = apiResponse.data;
res.render("results.ejs", { data: data });
})
.catch((err) => {
// handle error
console.log(err);
})
.then(() => {
// always executed
});
});
app.listen(3000, () => console.log("Server started at http://localhost:3000"));

Related

TypeError: Cannot set properties of undefined (Prismic DOM)

I'm encountering this error "TypeError: Cannot set properties of undefined (setting 'PrismicDOM')" in my local website.
I'm trying to integrate Prismic in my project where i'm using prismic-dom but it doesn't seem to work.
This is the code in my app.js can you tell me how to resolve this problem?
require('dotenv').config()
console.log(process.env.PRISMIC_ENDPOINT, process.env.PRISMIC_CLIENT_ID)
const express = require('express')
const app = express()
const path = require('path')
const port = 3000
const Prismic = require('#prismicio/client')
const PrismicDOM = require('prismic-dom')
const initApi = req => {
return Prismic.getApi(process.env.PRISMIC_ENDPOINT, {
accessToken: process.env.PRISMIC_ACCESS_TOKEN,
req
})
}
const handlelinkResolver = doc => {
// Define the url depending on the document type
// if (doc.type === 'page'){
// return '/page/' + doc.uid;
// } else if (doc.type === 'blog_post'){
// return '/blog/' + doc.uid;
// }
// Default to homepage
return '/'
}
app.use((req, res, next) => {
res.locals.ctx = {
endpoint: process.env.PRISMIC_ENDPOINT,
linkResolver: handlelinkResolver
}
// add PrismicDOM in locals to access them in templates.
req.locals.PrismicDOM = PrismicDOM
next()
})
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug')
app.get('/', (req, res) => {
res.render('pages/home')
})
app.get('/personaggi', (req, res) => {
res.render('pages/personaggi')
})
app.get('/detail/:uid', (req, res) => {
res.render('pages/detail')
})
app.get('/gioco', (req, res) => {
initApi(req).then(api => {
api.query(
Prismic.Predicates.at('document.type', 'gioco')
).then(response => {
console.log(response)
// response is the response object. Render your views here.
res.render('pages/gioco')
})
})
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})

TypeError: Cannot read property 'findAll' of undefined - Node.js + Postgresql

I have this problem when I try to get the data from the database
TypeError: Cannot read property 'findAll' of undefined
I made the web using react and node.js + postgresql. Postgres is in our server so I'm not using a localhost. I tried some other post but anything works.
Server.js
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
var corsOptions = {
origin: "http://localhost:3000",
};
app.use(cors(corsOptions));
// parse requests of content-type - application/json
app.use(bodyParser.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// simple route
app.get("/", (req, res) => {
res.json({ message: "Welcome to bezkoder application." });
});
// set port, listen for requests
require("./routes/noticias.routes")(app);
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
controller.js
const db = require("../config/db.config");
const noticias = db.noticias;
// Retrieve all noticias from the database.
const getNews = (req, res) => {
noticias
.findAll({})
.then((data) => {
res.send(data);
})
.catch((err) => {
res.status(500).send({
message: err.message || "Some error occurred.",
});
});
};
module.exports = {
getNews,
};
Router
module.exports = (app) => {
const noticias = require("../controllers/noticias.controller.js");
var router = require("express").Router();
router.get("/", noticias.getNews);
app.use("/noticias", router);
};
Thanks for the help ^^
I don't know much about about knex. As far as I know from docs there is a select function not findAll in knex.
Docs: https://knexjs.org/#Builder-select
Please try following method and see what happens
// below line is not required;
// const noticias = datab.noticias;
// Retrieve all noticias from the database.
const getNews = (req, res) => {
datab
.select("column_name_1", "column_name_2", "...")
.from("noticias")
.then((data) => {
res.send(data);
})
.catch((err) => {
res.status(500).send({
message: err.message || "Some error occurred.",
});
});
};
PS: the findAll function is available in sequelize not knex.
Use db.select('*').from('users') to findAll

Getting frequent error while passing data from form to a URL in NodeJS the error is cannot post /urlname

this is my from page where I post to a URL articles but it gives me error that cannot POST/URL name
every time I want to save a new article it gives me same error cannot post/URL name
<form action="/routes/articles" method="post">
//here I simply used a partials!
{{>form}}
</form>
this is code where I get data through post method that is mentioned and then it is saved to the database const express = require('express');
const router = express.Router();
const Article = require("../model/schema")
router.get('/', (req, res) => {
res.send('hey !!');
});
router.get('/new', (req, res) => {
res.render('articleGenerator');
});
router.get("/:id",(req,res)=>{
})
router.post("/",async(req,res)=>{
const newArticle = new Article({
title:req.body.title,
description:req.body.description,
markdown:req.body.markdown
})
//this code saves new article that is send from form page mentioned above
try {
newArticle = await newArticle.save();
res.redirect(`/articles/${newArticle.id}`)
} catch (error) {
res.render("/articleGenerator",{articles:newArticle});
}
})
this is my main file that i run Note that I have exported one route articlesjs that saves data.
module.exports = router;
const express = require('express');
const app = express();
const mongoose = require("mongoose");
this is for data base mongoose//
mongoose.connect("mongodb://127.0.0.1:27017/blogging-site",{
useNewUrlParser:true,
useUnifiedTopology:true,
useCreateIndex:true
})
//here i get the routes of page that is saving the data
const theRoutes = require('./routes/articles')
app.use('/theroutes', theRoutes);
app.set('view engine', 'hbs');
app.get('/', (req, res) => {
res.render('index');
});
app.listen(3000, () => {
console.log('server is up and running!!');
});

I can't get my data back, The Post function is working fine, tested with postman

I can't get my data, Post function is working fine I'm using Postman for testing it. When I put localhost:3000/api/names/2, I get this error
Can not GET /api/names/2
const express = require('express');
const app = express();
var cors =require('cors')
app.use(express.json()); app.use(cors())
const names = []
app.get('/api/names/', (req, res) => {
res.send(names);
} );
app.post('/api/names', (req, res) => {
const name = {
id: names.length,
name :req.body.name
};
names.push(name);
res.send(name);
});
app.listen(3000, () => console.log('port 3000'));
To GET
app.get('/api/names/:id', (req, res) => { res.send(names.filter(x => x.id == req.params.id););

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