I have the following code js and php
$.post("url.php", {
'action': 'add'
}, function (data) {
do something here with the data
});
and for the php I have sometinhg like this:
$action = $_POST['action'];
if($action == 'add'){
do something here
}
My question is - How do I do the same but for Node JS?
Thanks
$ npm install express body-parser --save
$ touch ./index.js
// in index.js
const express = require('express')
const bodyParser = require('body-parser');
const app = express()
// or .json() depending on your preference
app.use(bodyParser.urlencoded());
app.post('/', function (req, res) {
if(req.body.action === 'add') {
return res.send('Hello World!')
}
return res.send('Action not supported'); // or 404 or whatever.
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
$ npm start
Then, in a webpage
$.post("/", {
'action': 'add'
}, function (data) {
console.log(data); // should be "Hello World!"
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.