Javascript node.js 类型错误:路径必须是绝对路径或指定 root 到 res.sendFile [解析 JSON 失败]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26079611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
node.js TypeError: path must be absolute or specify root to res.sendFile [failed to parse JSON]
提问by IE8IsBetterThenGoogleChrome
[add] So my next problem is that when i try adding a new dependence (npm install --save socket.io). The JSON file is also valid. I get this error: Failed to parse json
[添加] 所以我的下一个问题是,当我尝试添加新的依赖项时(npm install --save socket.io)。JSON 文件也是有效的。我收到此错误:无法解析 json
npm ERR! Unexpected string
npm ERR! File: /Users/John/package.json
npm ERR! Failed to parse package.json data.
npm ERR! package.json must be actual JSON, not just JavaScript.
npm ERR!
npm ERR! This is not a bug in npm.
npm ERR! Tell the package author to fix their package.json file. JSON.parse
So I've been trying to figure out why this error has been returning. All of the files (HTML,JSON,JS) are inside the same folder on my desktop. I'm using node.js and socket.io
所以我一直在试图弄清楚为什么这个错误一直在返回。所有文件(HTML、JSON、JS)都在我桌面上的同一个文件夹中。我正在使用 node.js 和 socket.io
This is my JS file:
这是我的 JS 文件:
var app = require('express')();
var http = require('http').Server(app);
app.get('/', function(req, res){
res.sendFile('index.html');
});
http.listen(3000,function(){
console.log('listening on : 3000');
});
This is what is getting returned:
这是返回的内容:
MacBook-Pro:~ John$ node /Users/John/Desktop/Chatapp/index.js
listening on : 3000
TypeError: path must be absolute or specify root to res.sendFile
at ServerResponse.sendFile (/Users/John/node_modules/express/lib/response.js:389:11)
at /Users/John/Desktop/Chatapp/index.js:5:7
at Layer.handle [as handle_request] (/Users/John/node_modules/express/lib/router/layer.js:76:5)
at next (/Users/John/node_modules/express/lib/router/route.js:100:13)
at Route.dispatch (/Users/John/node_modules/express/lib/router/route.js:81:3)
at Layer.handle [as handle_request] (/Users/John/node_modules/express/lib/router/layer.js:76:5)
at /Users/John/node_modules/express/lib/router/index.js:234:24
at Function.proto.process_params (/Users/John/node_modules/express/lib/router/index.js:312:12)
at /Users/John/node_modules/express/lib/router/index.js:228:12
at Function.match_layer (/Users/John/node_modules/express/lib/router/index.js:295:3)
TypeError: path must be absolute or specify root to res.sendFile
at ServerResponse.sendFile (/Users/John/node_modules/express/lib/response.js:389:11)
at /Users/John/Desktop/Chatapp/index.js:5:7
at Layer.handle [as handle_request] (/Users/John/node_modules/express/lib/router/layer.js:76:5)
at next (/Users/John/node_modules/express/lib/router/route.js:100:13)
at Route.dispatch (/Users/John/node_modules/express/lib/router/route.js:81:3)
at Layer.handle [as handle_request] (/Users/John/node_modules/express/lib/router/layer.js:76:5)
at /Users/John/node_modules/express/lib/router/index.js:234:24
at Function.proto.process_params (/Users/John/node_modules/express/lib/router/index.js:312:12)
at /Users/John/node_modules/express/lib/router/index.js:228:12
at Function.match_layer (/Users/John/node_modules/express/lib/router/index.js:295:3)
回答by mscdex
The error is pretty clear, you need to specify an absolute (instead of relative) path and/or set rootin the config object for res.sendFile(). Examples:
错误很明显,您需要指定绝对(而不是相对)路径和/或root在配置对象中为res.sendFile(). 例子:
// assuming index.html is in the same directory as this script
res.sendFile(__dirname + '/index.html');
or specify a root (which is used as the base path for the first argument to res.sendFile():
或指定一个根(用作第一个参数的基本路径res.sendFile():
res.sendFile('index.html', { root: __dirname });
Specifying the rootpath is more useful when you're passing a user-generated file path which could potentially contain malformed/malicious parts like ..(e.g. ../../../../../../etc/passwd). Setting the rootpath prevents such malicious paths from being used to access files outside of that base path.
root当您传递可能包含格式不正确/恶意部分..(例如(例如../../../../../../etc/passwd))的用户生成的文件路径时,指定路径更有用。设置root路径可防止使用此类恶意路径访问该基本路径之外的文件。
回答by keeri
Try adding root path.
尝试添加根路径。
app.get('/', function(req, res) {
res.sendFile('index.html', { root: __dirname });
});
回答by Elias Goss
in .mjs files we for now don't have __dirname
在 .mjs 文件中,我们现在没有 __dirname
hence
因此
res.sendFile('index.html', { root: '.' })
回答by Michael Cole
If you trust the path, path.resolve is an option:
如果您信任该路径,则 path.resolve 是一个选项:
var path = require('path');
// All other routes should redirect to the index.html
app.route('/*')
.get(function(req, res) {
res.sendFile(path.resolve(app.get('appPath') + '/index.html'));
});
回答by saadi123
The error is pretty straightforward. Most likely the reason is that your index.html file is not in the root directory.
错误非常简单。最有可能的原因是您的 index.html 文件不在根目录中。
Or if it is in the root directory then the relative referencing is not working.
或者,如果它在根目录中,则相对引用不起作用。
So you need to tell the server exact location of your file. This could be done by using dirname method in NodeJs. Just replace your code with this one:
所以你需要告诉服务器你的文件的确切位置。这可以通过在 NodeJs 中使用 dirname 方法来完成。只需用以下代码替换您的代码:
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
Make sure that your add the slash "/" symbol before your homepage. Otherwise your path will become: rootDirectoryindex.html
确保在主页前添加斜杠“/”符号。否则你的路径会变成:rootDirectoryindex.html
Whereas you want it to be: rootDirectory/index.html
而你希望它是:rootDirectory/index.html
回答by Menuka Ishan
I solve this by using path variable. The sample code will look like below.
我通过使用路径变量解决了这个问题。示例代码如下所示。
var path = require("path");
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/index.html'));
})
回答by M.suleman Khan
If you are working on Root Directory then you can use this approach
如果您正在处理根目录,那么您可以使用这种方法
res.sendFile(__dirname + '/FOLDER_IN_ROOT_DIRECTORY/index.html');
but if you are using Routes which is inside a folder lets say /Routes/someRoute.jsthen you will need to do something like this
但是,如果您使用的是文件夹内的 Routes,/Routes/someRoute.js那么您将需要执行以下操作
const path = require("path");
...
route.get("/some_route", (req, res) => {
res.sendFile(path.resolve('FOLDER_IN_ROOT_DIRECTORY/index.html')
});
回答by David Dehghan
In Typescript with relative path to the icon:
在带有图标相对路径的打字稿中:
import path from 'path';
route.get('/favicon.ico', (_req, res) => res.sendFile(path.join(__dirname, '../static/myicon.png')));
回答by Nagnath Mungade
It will redirects to index.html on localhost:8080 call.
它将在 localhost:8080 调用上重定向到 index.html。
app.get('/',function(req,res){
res.sendFile('index.html', { root: __dirname });
});
回答by Abhishek saharn
This can be resolved in another way:
这可以通过另一种方式解决:
app.get("/", function(req, res){
res.send(`${process.env.PWD}/index.html`)
});
process.env.PWDwill prepend the working directory when the process was started.
process.env.PWD将在进程启动时预先添加工作目录。

