使用Express Node JS时如何从node_modules导入包

时间:2020-09-30 22:56:40

标签: javascript node.js express npm import

导入软件包时,会出现以下错误:

未捕获的TypeError:无法解析模块说明符“ axios”。 相对引用必须以“ /”、“./”或“ ../”开头。

,并在添加“ ./”,“ ../” 时出现此错误

获取http:// localhost:8080 / js / axios net :: ERR_ABORTED 404(未找到)

package.json

{
  "type": "module",
  "name": "fives",
  "version": "1.0.0",
  "description": "game",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node ./app.js"
  },
  "author": "ayah alrifai",
  "license": "ISC",
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-preset-es2015": "^6.0.15",
    "rimraf": "^3.0.2"
  },
  "dependencies": {
    "axios": "^0.19.2",
    "express": "^4.17.1",
    "socket.io": "^2.3.0",
    "socket.io-client": "^2.3.0"
  }
}

app.js

import http from "http";
import express from "express";
import io from "socket.io-client";
import path from 'path';

const app=express();
const port="8080";

app.use('/image', express.static('./public/img'));
app.use('/css', express.static('./public/css'));
app.use('/js', express.static('./js'));

app.get('/wait', (req, res)=> {
    res.sendFile(path.join(path.resolve()+'/html/await.html'));
});

app.get('/play', (req, res)=> {
    res.sendFile(path.join(path.resolve()+'/html/play.html'));
});

app.listen(port);

wait.js

import {getWaitedPlayers,createUser,deleteUser,isSelected,action} from "./fivesApi.js";
//code

fivesApi.js

import axios from "axios";
//code

.
├── html
│   ├── wait.html
│   └── play.html
├── app.js
├── js
│   ├── wait.js
│   ├── fivesApi.js
│   └── play.js
├── node_modules
├── package.json
├── package-lock.json
└── public
    ├── css
    │   └── fives.css
    └── img
        ├── 2.png
        ├── 5.png
        └── ayah.png

1 个答案:

答案 0 :(得分:0)

花了2个小时终于找到了解决方案,您要做的第一件事是

"delete"

然后package.json添加以下两行代码

'delete'

最终npm运行开发者。

如果您仍然遇到问题,please open this链接可以为我节省很多时间。