facing problem while importing files in nodejs - node.js

I don't know what's going wrong with these extensions, when I provide the extension ".js" the app runs fine but it gives a warning on that line saying Unexpected use of file extension "js" for "./models/user.js", but when I remove the extension the whole app crashes and says Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'F:\React\AuthenticationApp\backend\src\models\user' imported from F:\React\AuthenticationApp\backend\src\index.js, I know that files can be imported in node.js without providing the extension but I just know-how
here's my code
// eslint-disable-next-line no-unused-vars
import express from 'express'
import User from './models/user'
import './db/mongoose'
const app = express()
const port = 4000
app.use(express.json())
app.post('/users', (req, res) => {
const user = new User(req.body)
user
.save()
.then(() => {
res.send(user)
console.log(user)
})
.catch((e) => {
res.status(401).send(e)
})
})
app.listen(port, () => {
console.log(`Server is up on ${port}`)
})
and this is package.json
{
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "src/index.js",
"type": "module",
"scripts": {
"build": "babel ./src --out-dir ./build",
"start": "nodemon --exec babel-node src/index.js",
"dev": "nodemon src/index.js",
"lint": "eslint ."
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/cli": "^7.13.16",
"#babel/core": "^7.13.16",
"#babel/node": "^7.13.13",
"#babel/preset-env": "^7.13.15",
"#babel/runtime": "^7.13.17",
"eslint": "^7.25.0",
"eslint-config-airbnb-base": "^14.2.1",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-prettier": "^3.4.0",
"nodemon": "^2.0.7",
"prettier": "^2.2.1"
},
"dependencies": {
"express": "^4.17.1",
"mongoose": "^5.12.6",
"validator": "^13.6.0"
}
}

Adjust your eslint config with this rule:
"rules": {
"import/extensions": [
"error",
{
"js": "ignorePackages"
}
]
},
Detailed description of the rule is in this page.
That way a nodejs will successfully run, eslint will not show error.
CommonJS modules are still able to be without extension in 'require' functions.
But you have to specify an extension of ESmodule when using 'import' (except 'Bare specifiers' like 'some-package'), this is according to nodejs docs.

Related

npm script to both build typescript files and run after deploying to AWS EB environment

I want AWS EB to automatically build and run my files without me having to explicitly build everytime I push to git repo. I've tried placing this in "scripts" in package.json:
"start": "tsc build && node build/index.js"
The outDir specified in my tsconfig.json is build. This unfortunately didn't work and I get 'Degraded' health status. I know this is definitely the problem with my web server, because I tried manually building and placing node build/index.js in the "start" script, and it worked.
Here's my package.json:
{
"name": "woocommerce-api",
"version": "1.0.0",
"description": "",
"main": "src/index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "npx tsc && node build/index.js",
"dev": "nodemon -r dotenv/config src/index.ts",
"deploy": "npm run build && node build/index.js",
"build": "npx tsc"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"#types/node": "^18.7.18",
"cors": "^2.8.5",
"dotenv": "^16.0.2",
"express": "^4.18.1",
"helmet": "^6.0.0",
"nodemon": "^2.0.20"
},
"devDependencies": {
"#types/cors": "^2.8.12",
"#types/express": "^4.17.14",
"#types/helmet": "^4.0.0",
"#typescript-eslint/eslint-plugin": "^5.38.0",
"#typescript-eslint/parser": "^5.38.0",
"eslint": "^8.23.1",
"ts-node": "^10.9.1",
"typescript": "^4.8.3"
}
}
And my simple app with a get path at home, and a post path at /hook to consume webhooks.
import express, { Response, Request } from "express";
import cors from "cors";
import helmet from "helmet";
const app = express();
app.use(cors());
app.use(helmet());
app.use(express.json());
const port = process.env.PORT || 8081;
app.get("/", (req: Request, res: Response) => {
res.send({ message: "Hello world1234" });
});
app.post("/hook", (req: Request, res: Response) => {
console.log(req.body);
res.status(200).send({ message: "success" });
});
app.listen(port, () => {
console.log(`Listening on port ${port}...`);
});
Would appreciate the help.

Deploy To Heroku Successful But Then Socket IO Error In Terminal

I deployed react app successfully to Heroku but when click app link in terminal new window displays "Application Error" and error message in terminal states the following:
"import { Server } from 'socket.io'; SyntaxError: The requested module 'socket.io' does not provide an export named 'Server'
Server.js
import http, { request } from 'http';
import { Server } from 'socket.io';
const httpServer = http.Server(app);
const io = new Server(httpServer, { cors: { origin: '*' } });
const users = [];
package.json
{
"name": "app",
"type": "module",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"heroku-postbuild": "cd frontend && npm install && npm run build",
"start": "nodemon --watch backend --exec node --experimental-modules backend/server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"dotenv": "^16.0.1",
"engine.io-client": "^6.2.2",
"express": "^4.18.1",
"express-async-handler": "^1.2.0",
"jsonwebtoken": "^8.5.1",
"mailgun-js": "^0.22.0",
"mongoose": "^6.4.0",
"multer": "^1.4.5-lts.1",
"socket.io": "^4.5.1",
"socket.io-client": "^4.5.1"
},
"devDependencies": {
"nodemon": "^2.0.18"
},
"engines": {
"node": "12.4.0",
"npm": "6.9.0"
}
}

I am getting an error GET http://localhost:3000/api/products 404 (Not Found)

Well, there are lots of questions in StackOverflow about this error I've seen all of them none of them is working for me.
I'm using react with redux trying to fetch some products. my backend server node is running on port 5000 and I'm using concurrently to start both servers at the same time whenever I'm trying fetch the data its using port 3000 where is my frontend running. Please somebody help me to solve this issue
package.json file
{
"name": "proshop",
"version": "1.0.0",
"description": "MERN application named proshop",
"main": "server.js",
"type": "module",
"scripts": {
"start": "node backend/server",
"server": "nodemon backend/server",
"client": "npm start --prefix frontend",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"data:import": "node backend/seeder",
"data:destroy": "node backend/seeder -d"
},
"keywords": [
"NodeJS",
"ExpressJs",
"React",
"Redux",
"MongoDb"
],
"author": "Narayan Maity",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"colors": "^1.4.0",
"concurrently": "^5.3.0",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"express-async-handler": "^1.1.4",
"mongoose": "^5.10.9"
},
"devDependencies": {
"nodemon": "^2.0.6"
}
}
Here is my productsAction.js file
import axios from 'axios';
import {
PRODUCT_LIST_FAIL,
PRODUCT_LIST_REQUEST,
PRODUCT_LIST_SUCCESS,
} from '../constants/productConstants';
export const listProducts = () => async (dispatch) => {
try {
dispatch({ type: PRODUCT_LIST_REQUEST });
const { data } = await axios.get('http://localhost:5000/api/products');
dispatch({ type: PRODUCT_LIST_SUCCESS, payload: data });
} catch (error) {
dispatch({
type: PRODUCT_LIST_FAIL,
payload:
error.response && error.response.data.message
? error.response.data.message
: error.message,
});
}
};
If I use the full address like HTTP://localhost:5000/api/products its giving me CORS error
It would be much more easier and focus if you add "proxy": "http://localhost:5000" in your client or react project folder, like so:-
client/package.json
{
"name": "projectname",
"version": "0.1.0",
"private": true,
"dependencies": {
...}
"proxy": "http://localhost:5000"
}
Then you can just do:-
await axios.get('/api/products') // straight away use whatever path you've specified

Refused to load the image 'https://diary2020.herokuapp.com/favicon.ico'

I used MERN(MongoDb, Express, React js, Node) technology for my app. It works locally fine. but When I deployed in heroku I am getting internal server error. I might made mistake in setup but I can't see it.
In google Chrome console I got this error: Refused to load the image 'https://diary2020.herokuapp.com/favicon.ico' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'img-src' was not explicitly set, so 'default-src' is used as a fallback.
When I used Heroku logs I got this:
This is my server setup:
require("dotenv").config();
const express = require("express");
const cors = require("cors");
const morgan = require("morgan");
const app = express();
const logs = require("./src/logs.js/logs");
const mongoose = require("mongoose");
const path = require("path");
const helmet = require("helmet");
//middlewares
app.use(cors());
app.use(morgan("dev"));
app.use(express.json());
app.use(helmet());
//connect to db
mongoose
.connect(process.env.MONGODB_URI, {
useUnifiedTopology: true,
useNewUrlParser: true
})
.then(() => console.log("DB Connected!"))
.catch(err => {
console.log(err);
});
app.use("/api", logs);
app.use(express.static(__dirname + "build")); //
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "build", index.html));
});
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Server is running port ${port}`);
});
In my client folder first run npm run build then I cut it and pasted it outside of the client. Then I connected to server. As you can above. But it does not recognize the build's index.html
This is my backend package.json
{
"name": "form",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"start": "node server.js",
"server": "node server.js",
"client": "npm start --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\""
},
"author": "alak",
"license": "MIT",
"dependencies": {
"concurrently": "^5.1.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"helmet": "^3.21.3",
"heroku": "^7.39.0",
"jquery": "^3.4.1",
"mongoose": "^5.9.3",
"morgan": "^1.9.1",
"path": "^0.12.7",
"react-router-dom": "^5.1.2", //I MISTAKENLY INSTALLED IT.BUT I THINK IT SHOULD NOT BE A PROBLEM
"react-transition-group": "^4.3.0" //I MISTAKENLY INSTALLED IT. BUT I THINK IT SHOULD NOT BE A PROBLEM
}
}
This is React's package.json
{
"name": "client",
"version": "0.1.0",
"engines": {
"node": "13.10.1",
"npm": "6.13.7"
},
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.3.2",
"#testing-library/user-event": "^7.1.2",
"moment": "^2.24.0",
"react": "^16.13.0",
"react-dom": "^16.13.0",
"react-scripts": "3.4.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"proxy": "http://localhost:5000",
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
The ReferenceError you're seeing is caused by index.html not being wrapped in quotations - node is trying to evaluate the html property of an object named index which I'm willing to bet is not what you meant.
app.use(express.static(__dirname + "build")); //
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "build", index.html)); // <- try "index.html"
});
The probable reason why you getting this error is likely because you've added /build folder to your .gitignore file or generally haven't checked it into git. So when you git push heroku master, build folder you're referencing don't get push to heroku. And that's it shows this error.
T its work properly locally

Deployed my app on heroku but got error: Failed to load resource: net::ERR_CONNECTION_REFUSED

My app's front-end is Reactjs and backend is Node js. I used express server and graphql-express server. I deployed my app successfully. But it starts with data is loading and then nothing shows. But if I run locally npm start then the heroku app is start working.
This is the error I get it in browser
This is my server's package json file. If i run in terminal npm run dev. It opens my react js app.
{
"name": "backend",
"version": "1.0.0",
"description": "personish vol 2",
"main": "server.js",
"scripts": {
"start": "node server.js",
"server": "node server.js",
"client": "npm start --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\""
},
"author": "Alak",
"license": "ISC",
"dependencies": {
"concurrently": "^5.0.2",
"cors": "^2.8.5",
"express": "^4.17.1",
"express-graphql": "^0.9.0",
"graphql": "^14.5.8",
"pg": "^7.15.1",
"pg-hstore": "^2.3.3",
"sequelize": "^5.21.3"
}
}
This is my react's package json
{
"name": "client",
"version": "0.1.0",
"private": true,
"engines": {
"node": "13.3.0",
"npm": "6.13.0"
},
"dependencies": {
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.3.2",
"#testing-library/user-event": "^7.1.2",
"apollo-boost": "^0.4.7",
"axios": "^0.19.0",
"firebase": "^7.6.1",
"graphql": "^14.5.8",
"pg": "^7.15.1",
"react": "^16.12.0",
"react-apollo": "^3.1.3",
"react-dom": "^16.12.0",
"react-dropzone": "^10.2.1",
"react-redux": "^7.1.3",
"react-redux-firebase": "^3.0.5",
"react-router-dom": "^5.1.2",
"react-scripts": "3.3.0",
"redux": "^4.0.4",
"redux-firestore": "^0.11.0",
"redux-thunk": "^2.3.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
This is my express and graphql-express server.
const express = require("express");
const app = express();
const graphqlHTTP = require("express-graphql");
const schema = require("./schema");
const cors = require("cors");
const path = require("path");
app.use(cors());
app.use(
"/graphql",
graphqlHTTP({
schema,
pretty: true,
graphiql: true
})
);
app.use(express.static(path.join(__dirname, "build")));
app.get("/*", (req, res) => {
res.sendFile(path.join(__dirname, "build", "index.html"));
});
const port = process.env.PORT || 8081;
app.listen(port, () =>
console.log(`✅ Example app listening on port ${port}!`)
);
This is my react's app file. Where I use Apollo boost to connect with react app and node js app. I think the error comes from here, dont know how to fix it
import React from "react";
import { ApolloClient, HttpLink, InMemoryCache } from "apollo-boost";
import { ApolloProvider } from "react-apollo";
const client = new ApolloClient({
link: new HttpLink({
uri: "http://localhost:8081/graphql"
}),
cache: new InMemoryCache()
});
This is my heroku app
https://databaseapp2020.herokuapp.com/
your heroku dyno/app would have a name, you would use that to hit your graphql from say a graphiql playground on your laptop, or your react-app... if your heroku app was actually named databaseapp2020 and running then you would use the following assuming your cors was setup properly in the dyno environment variables
https://databaseapp2020.herokuapp.com/graphql

Resources