ExpressJS不调用ajax的get方法

时间:2019-06-26 19:14:02

标签: node.js express

我使用Express Application Generator

创建了一个ExpressJS应用示例。

我想调用localhost:3000 / data来获取一些数据。我将这些代码添加到app.js:

app.get('/data', function(req, res){
  debug("get data");
});

我也在客户端js文件中发出Ajax请求:

$.ajax({
    url: 'http://localhost:3000/data/',
    //url: 'http://localhost:3000/data', -> also not work
    type:'GET',
    dataType: 'json',
    success: (data) => {
        console.log("get data from client js", data);
    }
});

但是我的app.get方法从不调用。 GET /data/ 404写在控制台屏幕中。另外,当我在浏览器中输入http://localhost:3000/data时,我也遇到了Not Found错误。我该如何解决?


我的www文件:

#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('myapp:server');
var http = require('http');

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;

  debug('Listening on ' + bind);
}

1 个答案:

答案 0 :(得分:0)

我不确定您的问题所在,因为没有足够的代码来确定问题所在。相反,我编写了一个简单的快递服务器供您使用:

const express = require('express');
const bodyParser = require('body-parser');
const CORS = require('cors');

const app = express();

app.use(bodyParser.json());
app.use(CORS());


app.get('/data', (req, res) => {
    res.json({message: "working"});
});


app.listen(5000, () => {
    console.log('Server listening on port 5000');
});