如何运行此API服务器代码

时间:2018-03-27 19:21:13

标签: node.js api

我是节点Js世界的新手,并且目前正在学习基础知识,我在网上找到了这个代码,我想运行它并查看结果,但我不是'能够运行它,你能帮帮我吗? 代码基本上得到了Parsetime和unixtime,但是我不知道要传递什么参数,我尝试了node api.js 3000我试过node api.js '/api/unixtime仍然没有工作,

var http = require('http');
var url = require('url');
var port = process.argv[2];

function parseTime (time) {
  return {
    hour: time.getHours(),
    minute: time.getMinutes(),
    second: time.getSeconds()
  };}

function unixTime (time) {
  return {unixtime: time.getTime()};
} 
function parseQuery (url) {
  switch (url.pathname) {
    case '/api/parsetime':
      return parseTime(new Date(url.query.iso))
    case '/api/unixtime':
      return unixTime(new Date(url.query.iso))
    default: return 'please enter a valid endpoint url'
  }}

var server = http.createServer(function (request, response) {
  // Request handeling logic.
  if (request.method === 'GET') {

    // write request status and content type to resposne head
    response.writeHead(200, {'Content-Type': 'application/json'})

    var urlobj = url.parse(request.url, true);
    response.end(JSON.stringify(parseQuery(urlobj)));

  } else {
    response.writeHead(405);
    response.end();
  } });

server.listen(port, function () {
  console.log('Server listening on http://localhost:%s', port)
})

1 个答案:

答案 0 :(得分:0)

我刚刚对您的脚本进行了一些更改,它确实有效!下面是脚本 / *********************************** /

const http = require('http')
const port = 3000
var url = require('url');
const requestHandler = (request, response) => {
  console.log(request.url)
  response.end('Hello Node.js Server!')
}

function parseTime (time) {
    return {
      hour: time.getHours(),
      minute: time.getMinutes(),
      second: time.getSeconds()
    };}

  function unixTime (time) {
    return {unixtime: time.getTime()};
  } 
  function parseQuery (url) {
    switch (url.pathname) {
      case '/api/parsetime':
                console.log(new Date());
        return parseTime(new Date())
      case '/api/unixtime':
        return unixTime(new Date())
      default: return 'please enter a valid endpoint url'
    }}

  var server = http.createServer(function (request, response) {
    // Request handeling logic.
    if (request.method === 'GET') {

      // write request status and content type to resposne head
      response.writeHead(200, {'Content-Type': 'application/json'})

      var urlobj = url.parse(request.url, true);
      response.end(JSON.stringify(parseQuery(urlobj)));

    } else {
      response.writeHead(405);
      response.end();
    } });

  server.listen(port, function () {
    console.log('Server listening on http://localhost:%s', port)
  })

/ *********************************** /

步骤1:在命令行中运行:node api.js

第2步:进入浏览器并点击http://localhost:3000/api/unixtimehttp://localhost:3000/api/parsetime