[英]How to $.post to Node.js
我有以下代码js和php
$.post("url.php", {
'action': 'add'
}, function (data) {
do something here with the data
});
对于 php 我有这样的东西:
$action = $_POST['action'];
if($action == 'add'){
do something here
}
我的问题是 - 除了 Node JS 我该怎么做?
谢谢
$ 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
然后在网页中
$.post("/", {
'action': 'add'
}, function (data) {
console.log(data); // should be "Hello World!"
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.