DEV Community

Sanket N Jain
Sanket N Jain

Posted on

I am getting undefined object when I use req.query.search in express

node js code:

var express = require("express");
const axios = require("axios");
var app = express();

app.set("view engine", "ejs");

app.get("/", function(req, res){
    res.render("search");
});

app.get("/results", async function(req, res){
    var Search = req.query.search;
    console.log(Search);
    var url = 'http://www.omdbapi.com/?s='+Search+'&apikey=thewdb';
    try{
        const response = await axios.get(url);
        res.render("results", {data:response.data});
    }
    catch(err){
        console.log(err);
    }
});

app.listen(3000, function(){
    console.log("sever listening to port 3000");
});

search.ejs code:

<h1>Search for a movie</h1>

<form action="/results" method="GET" name="search">
    <input type="text" placeholder="search term">
    <input type="submit">
</form>

results.ejs code:

<h1>Results!!</h1>

<% data["Search"].forEach(function(movie){ %>
    <li><%= movie["Title"] %></li>
<% }) %>  

I get undefined movie names:
Alt Text

Top comments (2)

Collapse
 
hangindev profile image
Jason Leung 🧗‍♂️👨‍💻

Hi Sanket! The name attribute should be placed on the input element.

<form action="/results" method="GET">
    <input type="text" placeholder="search term" name="search">
    <input type="submit">
</form>
Collapse
 
sanketnjain5 profile image
Sanket N Jain

Thank you!