对节点服务器进行ajax调用

时间:2018-01-18 07:01:34

标签: javascript jquery node.js ajax express

我是NodeJS的新手并尝试使用npm spotcrime包通过ajax调用点击按钮从用户输入位置获取犯罪数据。以下是包的npm文档页面上给出的包的用法。

var spotcrime = require('spotcrime');

// somewhere near phoenix, az 
var loc = {
lat: 33.39657,
lon: -112.03422
};

 var radius = 0.01; // this is miles 
spotcrime.getCrimes(loc, radius, function(err, crimes){

});

单独运行时可以正常运行并返回正确的犯罪json数据。但是我不明白如何通过单击按钮调用ajax来调用它。任何见解都会非常有用。在此先感谢:)

更新

这是我的服务器代码

var express = require('express');
var app = express();
var dataFile = require('./data/data.json');
var reload = require('reload');
var path = require('path');

app.set('port', process.env.PORT || 3000);
app.set('appData', dataFile);   
app.set('view engine', 'ejs');

app.set('views', __dirname + '/views');
app.use(express.static(path.join(__dirname, '/public')));
app.use(require('./routes/index'));
app.use(require('./routes/information'));
app.use(require('./routes/spotcrime'));


var server = app.listen(app.get('port'), function(){
console.log('Go to http://localhost:' + app.get('port')+ ' on your 
browser');

});

reload(app);

这是spotcrime.js文件

var express = require('express');
var router = express.Router();
var spotcrime = require('spotcrime');


router.get('/spotcrime', function(request, response){
var loc = {
lat: 33.39657,
lon: -112.03422
};

var radius = 0.01; // this is miles 

spotcrime.getCrimes(loc, radius, function(err, crimes){
response.send(crimes);
});


}); 

module.exports = router;

我在很长一段时间内尝试这个,但没有任何表现。请建议任何出路

2 个答案:

答案 0 :(得分:0)

使用此代码进行ajax调用

 var http = require('http');
    var request = require('request');
    request.post({
            url: "xxxxxxxxxxxx",
            method: "POST",
            json: true, // <--Very important!!!
            body: {}
        },
        function(error, response, body) {
            if (!error) {
                console.log(body.d);
            } else {
                console.log(error);
            }
        }
    );

答案 1 :(得分:0)

如果我理解正确,您希望从浏览器(前端)向服务器发送AJAX请求。这可以通过jQuery AJAX轻松完成,请参阅official documentation page。以下是您的示例:

<buttom class="send-request">Send AJAX request</button>

$(".send-request").click(function() {
    $.ajax({
      method: "GET", // since you are waiting for GET request on server
      url: "/spotcrime", // you might have to provide full path to your endpoint starting with https://127.0.0.1/spotcrime
      data: { Greetings: "Hello" } // data object can be deleted since you don't expect any parameters on server side
    })
    .done(function( msg ) {
      alert( "Response data: " + msg );
    });
});