[英]How to make ajax get/post request in express server?
下面是我的快递服务器。 我试图在ajax中发出get请求,但结果却失败了,即使我在开始时需要jquery。 它说$没有定义除了使用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); } }); }
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); });
您需要了解以下内容:
expressjs
是服务器端代码,因此它不能像这样使用jquery ajax。 jQuery.ajax()
只能在浏览器中加载页面时在视图中使用。 您需要使用一些视图引擎(如jade
来创建模板并使用路由器在浏览器中推送视图。 当您在浏览器中查看视图时,您可以对脚本文件进行引用,该脚本文件可以包含您的ajax代码,以便您拥有帖子和注释。
更新 @Someone,快速框架在Node中设置Web服务器非常流行。 您可以使用不同的渲染引擎来渲染视图并将信息传递给用户。 这是一个非常简单的例子,来自Express网站,听取两个网址(/ posts和/ comments)。
var express = require('express');
var app = express();
app.get('/posts', function (req, res) {
res.send('Render posts!');
});
app.get('/comments', function (req, res) {
res.send('Render comments');
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
尝试这样的事情:
function() {
// Simple POST request example (passing data) :
$http.post("/createProject/"+ id +"", {
projectTitle: pTitle,
userID : id
}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
$scope.getProjects();
console.log("project created");
console.log("this is the response data " + data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};
另请注意。 你将从外部JavaScript文件中调用它。 一个Express服务器只有“路由”,而外部javascript文件可以在这些路由上执行HTTP调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.