gpt4 book ai didi

javascript - 如何在 express 服务器中发出 ajax get/post 请求?

转载 作者:数据小太阳 更新时间:2023-10-29 05:05:30 26 4
gpt4 key购买 nike

下面是我的 express 服务器。我试图在 ajax 中发出一个 get 请求,但结果失败了,即使我一开始就需要 jquery。它说 $ is not defined 除了使用 jquery ajax,我还可以使用什么来从 RESTful API url 进行 API 调用?

var express = require('express');
var requestHandler = require('./requestHandler');
var app = express();
var path = require('path');


app.use(express.static(path.join(__dirname, '../client')));
app.get('/homepage', requestHandler.getData);

var port = process.env.PORT || 3000;
app.listen(port);
console.log("Server running at: http://localhost:" + port);

// request handler file:

var express = require('express');
var url = "http://jsonplaceholder.typicode.com/";

module.exports.getData = function (req, res){
$.ajax({
method: 'GET',
url: url+'posts',
success: function(data) {
console.log(data);
res.send(data);
}
});
}
module.exports.getComments = function(userId){
$.ajax({
method: 'GET',
url: url+'/comments',
success: function(data) {
console.log(data);
}
});
}

最佳答案

HTTP GET Request in Node.js Express

var http = require('http');
var options = {
host: 'www.google.com',
path: '/index.html'
};

var req = http.get(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));

// Buffer the body entirely for processing as a whole.
var bodyChunks = [];
res.on('data', function(chunk) {
// You can process streamed parts here...
bodyChunks.push(chunk);
}).on('end', function() {
var body = Buffer.concat(bodyChunks);
console.log('BODY: ' + body);
// ...and/or process the entire body here.
})
});

req.on('error', function(e) {
console.log('ERROR: ' + e.message);
});

关于javascript - 如何在 express 服务器中发出 ajax get/post 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32963736/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com