node.js - 使用 ajax 向 nodejs 发送 post 请求
问题描述
我正在尝试使用 ajax 向 nodeJS 发送数据:
var express = require('express');
var app = express();
var path = require('path')
app.use(express.urlencoded())
const router = express.Router();
router.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/client.html'));
//__dirname : It will resolve to your project folder.
});
//add the router
app.use('/', router);
app.post('/endpoint', function(req, res){
var obj = {};
console.log('body: ' + JSON.stringify(req.body.title));
res.send(req.body);
});
app.listen(3000);
应用程序.js
<html>
<head>
<title>jsonp test</title>
<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
$(function(){
$('#select_link').click(function(e){
e.preventDefault();
console.log('select_link clicked');
var data = {};
data.title = "title";
data.message = "message";
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
url: 'http://localhost:3000/endpoint',
success: function(data) {
console.log('success');
console.log(JSON.stringify(data));
}
});
});
});
</script>
</head>
<body>
<div id="select_div"><a href="#" id="select_link">Test</a></div>
</body>
</html>
我不明白为什么我没有在服务器端接收数据,有人提示我该怎么做?
提前致谢 !
解决方案
发送data
没有stringify
$.ajax({
type: 'POST',
data: data,
contentType: 'application/json',
url: 'http://localhost:3000/endpoint',
success: function (data) {
console.log('success');
console.log(JSON.stringify(data));
}
});
data.title
您将可以访问req.body.title
app.post('/endpoint', function (req, res) {
console.log('body: ' + req.body.title);
//...
});
推荐阅读
- react-native - 屏幕上的多个 panresponder 管理不同的区域(同时)
- html - Safari 视口适合封面不占用整个屏幕高度
- swift - TableViewCell 的约束在新单元格创建时返回 nil
- firebase - 注册 Firebase Flutter 时更新 displayName
- sql - SQL - 计算用户数
- colors - 显示与行颜色对应的seaborn clustermap的图例
- xcode - Xcode 默认启用文件访问
- angular - Angular 和 NGXS 实验室操作正在执行:ExpressionChangedAfterItHasBeenCheckedError
- applepay - Apple Pay 商户标识符缺少编辑链接
- python - Pygame 中的音频文件失真