How to pass GET form data to Express? - javascript

I have a form
<form action="./search" method="GET">
<div class="form-group text-center">
<input type="text" name="keyword" placeholder="Job Title" />
<button type="submit" class="btn btn-primary">Find Jobs</button>
</div>
</form>
If I enter "akron" in the form and submit and pass it to this next method it returns "Cannot GET /search?keyword=akron"
router.get('/search/:keyword', function(req, res) {
res.send('hello ' + req.params.keyword + '!');
})
But if I type http://localhost:3000/search/akron it will return the "hello akron!"
What is the correct way to pass the parameters?

Change to
action="/search"
The "./blah" syntax with dot in front is for files.
Also change to
router.get("/search" //...
and use req.query

Related

Error on trying to override POST method with PUT (Method Not Allowed)

I am experiencing a "Method Not Allowed" issue when trying to override my POST request with PUT (for updating information in my blog). I already installed method override for koa.
HTML:
<div class="create-message content">
<form action="/messages/edit/<%= message.id %>?_method=PUT" method="POST">
<label for="title">Message title:</label>
<input required value="<%= message.title %>" type="text" id="title" name="title" required>
<label for="snippet">Message snippet:</label>
<input required value="<%= message.snippet %>" type="text" id="snippet" name="snippet" required>
<label for="body">Message body:</label>
<input required value="<%= message.body %>" type="text" id="body" name="body" required>
<button>Update</button>
</form>
My routs are the following:
//edit message
router.get('/messages/edit/:id', async (ctx, next) => {
const id = ctx.params.id;
const result = await MessageModel.findById(id)
await ctx.render('edit', {
title: 'Messages',
message: result
})
});
The code above runs well, but after I click on submit button, "Method Not Allowed" issue occurs instead of running this:
//update edited message
router.put('/messages/edit/:id', async (ctx, next) => {
MessageModel.findByIdAndUpdate(ctx.params.id, ctx.request.body, {new:true}, (err:any, result:any) => {
})
return ctx.redirect('/');
});
Please share your thoughts on this issue.
Thank you
Make sure you add the following to your app.js (index.js) file.
app.use(methodOverride('_method'));
You can't set the form method to PUT, it's either GET or POST.
to send a PUT request you can use AJAX, via (for instance) the Fetch API
EDIT: my bad, you used the "tunneling" concept mentioned in that solution.
per this documentation, maybe try with
<form method="POST" action="/resource" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="_method" value="PUT">

How to add parameter in the html form action?

I have a form like this:
<form action="studyresults.show" method="POST">
...
...
<div style="clear: both;float: right;padding-top: 15px;padding-bottom:5px;">
<input id="submitButton" style="float:right;margin-top:-80px;" type="submit" class="btn btn-primary" value="Add" />
</div>
I want to add a parameter from url string like this:
<script>
function getQueryStringValue (key) {
return decodeURIComponent(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURIComponent(key).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
}
</script>
I would like to query the url with "token" string so I can pass "token" as part of POST request parameter when I click submit button. How can I achieve this?
Since you're using JSP, there's no need to involve JavaScript here. You can pull any query string parameter value directly using JSP's EL expression language.
<form action="studyresults.show" method="POST">
<input type="hidden" name="token" value="${param.token}" />
...
<div style="clear: both;float: right;padding-top: 15px;padding-bottom:5px;">
<input id="submitButton" style="float:right;margin-top:-80px;"
type="submit" class="btn btn-primary" value="Add" />
</div>
</form>
The above example adds the token value ${param.token} as a hidden <input> field which will get POSTed along with other field values when the form is submitted.

req.body with res.render getting incomplete Vaule

I am facing a strange issue - using req.body to send the form input to another page, data is getting rendered while using a single word in from input example: "FullName", however, with space example: "Full Name" getting an only first string (full)it ignoring the word after space.
how to fix this issue
<form class="" action="/addname" method="POST">
<div class="input-field col s5">
<i class="material-icons prefix">account_circle</i>
<input id="Name" type="text" name = "Name">
<label for="icon_prefix">Name</label>
</div>
<button class="waves-effect waves-light btn default" type="submit" name="action" >Next <i class="material-icons prefix">navigate_next</i></button>
</form>
app.js
server.post('/addname', (req, res) => {
const Name: req.body.Name;
res.render('Userinfo', {Name});
});
ejs
<p> <%=Name%></p>
Please update your app.js with the following code:
server.post('/addname', (req, res) => {
const {Name} = req.body
res.render('Userinfo', {Name});
});

Passing values from a view to Node without URL in Nodejs

I am using nodejs with express and ejs.
Every one on internet ask how to pass value from node to the view, but what about the opposite?
For example, I ask my user to input a string in a form, when the user clicks the button, how can I get this string without passing it as a parameter in the url?
The form:
<div class="container">
<form style="width:50%">
<div class="form-group">
<label for="text">Name of the product</label>
<input type="text" class="form-control" id="pName">
</div>
<div class="form-group">
<label for="text">Reciever</label>
<input type="text" class="form-control" id="reciever">
</div>
<div class="form-group">
<label for="text">Location</label>
<input type="text" class="form-control" id="location">
</div>
<!-- <div class="checkbox">
<label><input type="checkbox"> Remember me</label>
</div>-->
<button type="submit" class="btn btn-default">Submit</button>
</form>
The app.js
var express = require('express');
var app = express();
//ALL GLOBAL VARIABLES
var port = 8080;
app.get('/', function(req, res) {
res.render('index.ejs');
});
app.get('/barcode', function(req,res) {
res.render('barcode.ejs');
});
app.listen(port);
I know I can do this:
app.get('/url/:parameter', function(req.res) {
var foo = req.params.parameter;
}
But if I don't want to use the URL, is it possible to retrieve the data?
Use POST as a method for your html form
<form action="/myapi" method="post">
<input type="text" class="form-control" id="pName" name="pName">
<button type="submit" class="btn btn-default">Submit</button>
</form>
And then handle the client form "action" with app.post on the back end
app.post('/myapi', function(req, res) {
res.send('The pName is "' + req.body.pName + '".');
});
You can use POST method instead of GET. You need to change the route in your Express to
app.post('/url', function(req.res))
and add a method on your form
<form style="width:50%" method="POST">
If you use a POST request the parameters are not part of the URL. E.g.
app.post('/path', function(req, res) {
...
//You can retrieve the parameters of the POST request here
]);
You'll need the body-parser module to be able to get the POST parameters. Here's an answer about how to get the POST parameters once you've set up the route.
Your form should have a method and and action:
<form action="/path" method="POST">...</form>
From your question, In general if you want to get a value from the unique id, you will store that value as a global variable. so you can easily get the current user and user related details.

Issue with javascript retrieve form data for url

I am kind of new to javascript however I have created a submit form that I want to redirect me to a url based on form input. Here is my current code...
The issue I'm running into however is that the form is sending me the initial value rather than the updated form value (It is using "whatevs" no matter what).
HTML
<form id="Search-Form" onClick="genURL()"><label>Value: </label>
<input type="text" id="search" placeholder="Enter Value"></input>
<div id="search-buttons">
<input id="searchSubmit" value="whatevs" type="submit" tabindex="1" />
</div>
</form>
Javascript
function genURL() {
var searchSubmit = document.getElementById("searchSubmit").value;
window.location = "randomsite/view" + searchSubmit;
}
Add return and use onsubmit:
<form id="Search-Form" onsubmit="return genURL()"><label>Value: </label>
<input type="text" id="search" placeholder="Enter Value"></input>
<div id="search-buttons">
<input id="searchSubmit" value="whatevs" type="submit" tabindex="1" />
</div>
</form>
Revise function like so:
function genURL()
{
location.href = "randomsite/view" + document.getElementById("search").value;
return false;
}
If you were to use onclick, it would go on the button, not the form.

Categories