简体   繁体   English

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

[英]NodeJS - 'Error: Invalid URI “/”'

I'm using request-promise to request two JSON data files which exist locally in my local project directory folder. 我正在使用request-promise请求两个本地项目目录文件夹中本地存在的JSON数据文件。 ie: 即:

在此处输入图片说明

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 "/"', 但是,当尝试将数据传递到视图并且我的节点控制台输出'Error: Invalid URI "/"',时,我收到500个内部服务器错误'Error: Invalid URI "/"',

Please see below: 请看下面:

server.js 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: 然后在client.js上:

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

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? 为什么不使用Node.js( fs )中的文件系统模块来获取数据? When you call rp() , you should pass an absolute URI and not a local path. 调用rp() ,应传递绝对URI,而不是本地路径。

To use it in your code, you need to "promisify" the readFile function: 要在您的代码中使用它,您需要“承诺” readFile函数:

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 . 然后您就可以Promise.all

Why aren't you simply returning the variables? 为什么不简单地返回变量?

I mean: 我的意思是:

app.get('/data', function(req, res) {
    res.send({hotels, guests}); 
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM