node.js - 使用 NodeJS 的 Ajax 请求处于挂起状态
问题描述
我正在尝试通过单击按钮进行 ajax 调用...但是调用没有到达节点层。HTML 标记:显示最新的手机
应用程序.js:
function postDetails() {
$.post('/api/users', {data: 'blah'}, function (data) {
console.log(data);
});
}
服务器.js
http.createServer(function(req, res) {
if(req.url == '/') {
fs.readFile("index.html", function(err, html) {
res.end(html);
});
} else if(req.url.match("\.css$")) {
var cssPath = path.join(__dirname, 'public', req.url);
var fileStream = fs.createReadStream(cssPath, 'UTF-8');
res.writeHead(200, {"Content-Type" : "text/css"});
fileStream.pipe(res);
} else if(req.url.match("\.js$")) {
var cssPath = path.join(__dirname, 'public', req.url);
var fileStream = fs.createReadStream(cssPath, 'UTF-8');
res.writeHead(200, {"Content-Type" : "text/javascript"});
fileStream.pipe(res);
}
}).listen(8000);
app.post('/api/users', function(req, res) {
console.log('KKKKKKKKKKuuuuuuuuuuuuuuKKKKKKK');
router.post('/', function (req, res) {
res.set('Content-Type', 'application/json');
var jsonData = JSON.stringify(req.body);
res.status(201);
res.json();
});
});
解决方案
我认为这是因为您正在使用http创建服务器和侦听请求,并尝试使用app处理路由(假设 Express 对象)。
所以要么你应该在http.createServer 的回调函数中编写路由代码,就像这样 -
http.createServer(function(req, res){
if(req.url == '/api/users' req.method === 'POST'){
//your code here
}
});
或者您应该使用app
(快速方式)创建服务器
推荐阅读
- azure - Azure 广告身份验证回复 url 包含带有 .netcore 中间件的 http 而不是 https - 如何强制执行 https?
- vb.net - 尝试使用 SuggestAppend 取消选择组合框中的文本时出现奇怪的行为
- javascript - 修复 vue js 复选框过滤器
- sql - 以列查询一行数据
- ruby - 使用 Ruby 续集 gem 导入大型 .SQL 文件
- asp.net - ERR_HTTP2_INADEQUATE_TRANSPORT_SECURITY
- palantir-foundry - 有没有办法以编程方式从 .csv 设置数据集的架构
- netsuite - “SuiteScript 2.0 入口点脚本必须实现一种脚本类型函数”错误
- python - SSD 与 tmpfs 速度
- python - 从 Pandas 或 Python 中的总值进行串行计算