Why is my route making a receive request instead of a send request in a rough app?
Why is my route making a receive request instead of a send request in the crud app? I have a html form that makes a post to `/ api / zone '. But instead of the router doing the post function in my rest apriot, it makes the call.
Here's my form:
<form action="/api/zone" method="post"> <!-- The Crux of Rest API is really methods. It a contract in REST API!-->
<input type='text' name='name' placeholder='Name' /><br />
<input type='text' name='zipCodes' placeholder='Zip Code' /><br />
<input type='submit' value='Create Zone' />
</form>
My Api's:
router.get('/:resource', function(req, res, next) {
var resource = req.params.resource
if (resource == 'zone'){
ZoneController.find(req.query, function(err, results){
if (err) {
res.json({
confirmation: 'fail',
message: err
})
return
}
res.json({
confirmation: 'success1234',
results: results
})
});
}
})
router.post('/:resource', function(req, res, next){
var resource = req.params.resource
if (resource == 'zone') {
ZoneController.create(req.body, function(err, result){
if (err) {
res.json({
confirmation: 'fail',
message: 'Not Created.'
})
return
}
res.json({
confirmation: 'success',
results: result
})
})
}
})
I have the following versions of node and express:
node - 6.11
express - 4.15
source to share
This is a weird problem, but I've seen it happen in Rails, and I believe this is what is happening.
Basically, initially the correct request is sent in the POST and the correct handler is router.post
called. Then, however, that route handler cannot properly handle the inputs on the form and for some reason sends a redirect to the GET version of the route (note that your mail and receive routes are the same) instead of returning, say, 400 error stating that she can shape the process.
Now, to understand why it cannot process the form, note that your route handler uses a slug on /:resource
, that is, it req.params.resource
will return one line. And taking a look at your form action
listed here is /api/zone
. So what happens is the router interprets the whole string /api/zone
as slug, so when in the post handler you do req.params.resource
, the return value is from api/zone
and not zone
, for which you have an if check.
So why is it probably evaluating if
, failing, not knowing what to do, and sending a redirect to GET.
So you can fix this by doing some parsing / validation on the POST route and / or adding else
in an if statement to redirect somewhere or send an error message.
Hope this helps!
source to share