我尝试从expressJs中的api获取数据。我正在使用'请求'。我想通过一个表格发送请求,用户可以选择要查找的电影的标题。我不明白为什么req.body.title是空的。我也尝试过req.params.title但是没有工作
感谢您的帮助
这是search.ejs文件
<div class="container">
<div class="row">
<div class="col-md-4">
<form action="/search" method="GET">
<div class="form-group">
<label for="">Keyword to search</label>
<input class="form-control" type="text" placeholder="e.g. Harry Potter" name="lang">
</div>
<div class="form-group">
<label for="">Keyword to search</label>
<input class="form-control" type="text" placeholder="e.g. Harry Potter" name="title">
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary">
</div>
</form>
</div>
<div class="col-md-8">
<p>title</p>
<p> <% film.forEach((singleMovie) => { %>
<p> <%= singleMovie.title %></p>
<% }) %> </p>
</div>
</div>
这是app.js
我想将带有名称标题的输入文本字段的值传递给变量filmName,之后用户将被重定向到同一页面,并在页面右侧显示搜索结果
//APP VARIABLES AND IMPORTING
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var request = require('request');
var app = express();
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: true}));
mongoose.connect('mongodb://localhost/film_database', {useMongoClient: true});
mongoose.Promise = global.Promise;
//BASIC ROUTE
app.get('/', (req, res) => {
res.render('index');
});
app.get('/search', (req, res) => {
var filmName = req.body.title; => this should return the input text
console.log(filmName);
var baseAPIAddress = "https://api.themoviedb.org/3"
var searchAPI= "/search/movie?api_key={my_api_key}&language=fr&query=" + filmName + "&include_adult=false"
var searchRequest = baseAPIAddress + searchAPI;
var film = {};
request(searchRequest, (err, resp, body) => {
if (!err && res.statusCode == 200) {
var film = JSON.parse(body);
var titleArray = film['results']
res.redirect('search', {film: titleArray});
} else {
console.log('err is: ' + err);
}
});
});
//GET => index.js => /search
///SERVER
app.listen(3000, () => {
console.log('SERVER IS RUNNING AT LOCALHOST://3000');
d});
我不知道为什么我无法获得输入值,我尝试了不同的方法,但没有工作。我认为GET是正确的,因为我不想修改任何数据。
答案 0 :(得分:1)
您正在使用GET。 尝试 var filmName = req.query.title;