Node.js 当我试图通过表单中输入的数据编辑API URL并从API获取数据时,代码不起作用
大家好,我是nodejs和expressjs的初学者,我正在尝试根据表单中输入的值获取数据。并根据URL的值进行编辑,发送请求,获取数据并显示给页面。我写的代码,但它不工作 Index.ejsNode.js 当我试图通过表单中输入的数据编辑API URL并从API获取数据时,代码不起作用,node.js,api,express,ejs,restful-url,Node.js,Api,Express,Ejs,Restful Url,大家好,我是nodejs和expressjs的初学者,我正在尝试根据表单中输入的值获取数据。并根据URL的值进行编辑,发送请求,获取数据并显示给页面。我写的代码,但它不工作 Index.ejs <form action="/index" method="POST"> <label for="name">Enter json/xml: </label> <input type="text" name="name"&g
<form action="/index" method="POST">
<label for="name">Enter json/xml: </label>
<input type="text" name="name">
     <button type="submit">Submit</button>
</form>
请帮我找到解决方案我想您的bodyParser有问题
app.use(express.urlencoded({
extended: true
}));
app.post('/index', function(req, res){
res.render('form-data', {data : req.body});
request.post({
"headers": { "content-type": "application/json" },
"url": "http://mysafeinfo.com/api/data?list=englishmonarchs&format="+req.body.name,
}, (error, response, body) => {
if(error) {
return console.log(error);
}
data = JSON.parse(body);
});
console.log(req.body);
});
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
在应用程序之后添加这些。设置“查看引擎”、“ejs”
你的post功能应该是这样的
app.post('/', function(req, res){
request('http://mysafeinfo.com/api/data?list=englishmonarchs&format='+req.body.name, function (error, response, body) {
var data = JSON.parse(body);
console.log(req.body);
});
});
并确保在索引文件的表单中
因为您正在使用as req.body.name请添加更多信息!添加有关您所面临问题的更多信息。它不起作用对任何人都没有帮助:提供的信息很难帮助您,但可能您似乎正在发布/索引,并在/?@AntonioOrtells上使用express serve,先生,因为我正处于学习阶段,我不确定这些事情。我只是想找到在这种情况下运行代码的确切方法,我只想在表单中输入值,然后根据表单值调用api URL并获取数据并显示在其他模板文件上
app.post('/', function(req, res){
request('http://mysafeinfo.com/api/data?list=englishmonarchs&format='+req.body.name, function (error, response, body) {
var data = JSON.parse(body);
console.log(req.body);
});
});