【发布时间】:2021-04-22 09:42:33
【问题描述】:
编辑: Github 上的项目:https://github.com/jackphumphrey/medisearch
我对 NODEjs 很陌生,如果这是一个简单/愚蠢的问题,我很抱歉
我正在尝试发送带有 JQuery ($.post) 的 POST 请求,该请求位于:/public/javascripts/user.js
user.js 在 jquery 之后的 index.html 中调用
index.html 加载正常,但是 $.post 请求发送错误
我认为我的主要问题是我不知道在哪里(如节点中的位置)我想发送发布请求
我的目录: 主文件夹/
公共/index.html & 公共/javascripts/user.js
app.js & 路由/users.js、路由/index.js
user.js(位于 public/)
$.post('/users', JSON.stringify({username : 'data', useremail : 'data@data.com'}), function(response, status) {
}, "json")
.done(function(response) {
alert(response);
})
.fail(function(xhr, status, error) {
alert('error: ' + error + ' status: ' + status);
})
.always(function(response) {
console.log('^ RESPONSE: ' + response);
});
users.js(位于 routes/)
var express = require('express');
var router = express.Router();
router.post('/users', function(req, res) {
var userName = req.body.username;
var userEmail = req.body.useremail;
console.log('Username: ' + userName + ' Email: ' + userEmail);
res.send('Username: ' + userName + ' Email: ' + userEmail);
});
module.exports = router;
我在数字海洋@端口 8080 上运行它
【问题讨论】:
-
为了将 json 发送到服务器,您还需要设置适当的 Content-type 标头。在服务器端,您还需要一个 bodyParser
-
我将在哪个文件中以及该文件的哪个位置包含 bodyParser?我发布了 GitHub 链接,因此您可以查看完整的代码,如果有帮助的话。
标签: javascript jquery node.js express post