七度&光 2017-10-01 04:03 采纳率: 22.2%
浏览 586

NodeJS-'错误:无效的URI“ /”'

I'm using request-promise to request two JSON data files which exist locally in my local project directory folder. ie:

enter image description here

However, I am getting a 500 internal server error, when trying to pass the data to the view and my node console outputs 'Error: Invalid URI "/"',

Please see below:

server.js

    let express = require('express');
    let app = express();
    let path = require('path');
    const rp = require("request-promise");

    //STORE PATH for local JSON files on variables
    let guest = require('./public/data/Companies');
    let hotel = require('./public/data/Guests');

    app.set("port", process.env.PORT || 5000);

    //GET JSON
    //Question: Is it okay to pass uri:guest
    app.get('/data', function(req, res) {
        Promise.all([rp({uri: guest, json: true}), rp({uri: hotel, json: true})]).then(function([hotels, guests]) {
            //res.json({hotels, guests});
            res.send({hotels, guests});
            console.log(hotels, guests);
        }).catch(function(err) {
            console.log(err);
            res.status(500).end();
        });
    });


    //CATCHALL
    app.get("/*", function(req,res){
        let file = req.params[0] || "/views/index.html";
        res.sendFile(path.join(__dirname, "/public/", file));
    });

    //SET PORT
    app.listen(app.get("port"), function(){
        console.log("Listening on port: " , app.get("port"));
    });

then on client.js:

$(function() {
    $.ajax({
        type: "GET",
        url: "/data",
        success: function (res) {
            console.log(res);
        }
    });
});
  • 写回答

2条回答 默认 最新

  • Memor.の 2017-10-01 04:24
    关注

    Why do you use request to get the data? Why don't you use the filesystem module from Node.js (fs) to get the data? When you call rp(), you should pass an absolute URI and not a local path.

    To use it in your code, you need to "promisify" the readFile function:

    let readFileAsAPromise = function(filename){
      return new Promise(function(resolve, reject) {
        fs.readFile(filename, (data, err) => {
          if(err) reject(err);
          resolve(data)
        })
      })
    }
    

    You can then you Promise.all.

    评论

报告相同问题?

悬赏问题

  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)