How do you connect a html form to a api using node express?
My form looks like:
<form action="/api" id="myform" method="GET">
<fieldset id="question-set1" >
<input type="checkbox" id="option1">
<label for="option1">Option 1</label>
<input type="checkbox" id="option2">
<label for="option2">Option 2</label>
</fieldset>
<button type="submit" for="myform">Next</button>
</form>
My server.js is
const express = require('express');
const bodyParser = require('body-parser')
const routes = require('./routes/api')
const app = express();
app.use(bodyParser.json())
app.use("/", express.static( __dirname '/public' ))
app.use("/api", routes);
app.use(function(err, req, res, next){
console.log(err)
res.status(422).send({error:err.message})
})
app.listen(process.env.port || 4000, function(){
console.log("now listening on port 4000")
});
My api.js file (which is stored in the routes subdir) is:
const express = require('express');
const router = express.Router();
router.get('/api', function(req, res, next){
console.log('GET REQUEST')
res.send({type: 'GET'})
});
module.exports = router;
This produces a 'Cannot GET /api' error in the browser when I click the submit button.
Is the form Action attribute supposed to be equivalent to the path in the api.js file?
The end goal is to perform actions depending on user options when submitted, but for now, I am trying to get node to console log a test message 'GET REQUEST' and send a simple response, to know it is working.
CodePudding user response:
server.js file
As you are using GET method in your form, and your action is routing to '/api', create an endpoint as app.get('/api') and do you logic inside that. Form values can be read as req.body.(...)
app.get('/api', (req, res) => {
//your logic
})
CodePudding user response:
you can do it with a library called 'axios'.
I leave here this tutorial that I find excellent.