i did so many things to solve this problem, i didn't.
so i am asking some questions related to some error
when i run code server and client side without no error.
but the screen is blank and console display error :
[App.js:24] POST http://localhost:5000/authentication/verify 401 (Unauthorized)
https://github.com/ousecTic/pern-jwt-tutorial << the link
anyway, i just type the code below, but it doens't work.
app.js (client side)
import React, { Fragment, useState, useEffect } from "react";
import "react-toastify/dist/ReactToastify.css";
import {
BrowserRouter as Router,
Route,
Switch,
Redirect
} from "react-router-dom";
import { toast } from "react-toastify";
//components
import Login from "./components/Login";
import Register from "./components/Register";
import Dashboard from "./components/Dashboard";
toast.configure();
function App() {
const checkAuthenticated = async () => {
try {
const res = await fetch("http://localhost:5000/authentication/verify", {
method: "POST",
headers: { jwt_token: localStorage.token }
});
const parseRes = await res.json();
parseRes === true ? setIsAuthenticated(true) : setIsAuthenticated(false);
} catch (err) {
console.error(err.message);
}
};
server.js (server side)
const express = require("express");
const app = express();
const cors = require("cors");
//middleware
app.use(cors());
app.use(express.json());
//routes
app.use("/authentication", require("./routes/jwtAuth"));
app.use("/dashboard", require("./routes/dashboard"));
app.listen(5000, () => {
console.log(`Server is starting on port 5000`);
});
jwtauth (server side)
router.post("/verify", authorize, (req, res) => {
try {
res.json(true);
} catch (err) {
console.error(err.message);
res.status(500).send("Server error");
}
});
module.exports = router;
and i checked already below some things.
i just changed react/react-dorm and others package version in package.json
in the server/client side. cause it has been changed a lot so many errors occured.
so i make the package the same version.
And i checked DB connection / but it seems to work.
and this is my entire code : https://github.com/Ryandongyou/jwt_project_dongyou
thank you :)
Related
I have been getting this error in this small nodejs app while trying to learn using axios on the backend to make request. "unexpected end of file".
axios request file
import axios from "axios";
export const getData = async () => {
let data;
try {
const response = await axios.get(
"https://jsonplaceholder.typicode.com/users"
);
console.log(response);
data = response;
} catch (error) {
console.log(error.message);
return;
}
return data;
};
server.js
import express from "express";
import cors from 'cors';
import axios from "axios";
import { getData } from "./utils/getData.js";
const app = express();
app.use(cors());
app.use(express.json());
app.get("/", async (req, res) => {
let users;
users = await getData();
res.send(users);
})
app.listen(5000, () => {
console.log("server listening at port 5000");
})
You can add below header encoding to your request.
axios.get("url", {
headers: { "Accept-Encoding": "gzip,deflate,compress" }
});
the Brotli decompression bug was fixed in v1.2.2
Bro, go to Package.json--> in dependencies --> check for axios ---> Add 'axios' : '1.1.3'.
This will solve your issue.
I've been working with express for years, and I'm a bit rusty on the typescript side - however... I think I have gone blind! Its the first time I encounter this, so I must be doing something wrong...
My problem is this:
I have an endpoint called "/status".
When I call it, it will sometimes return OK;
And other times it will return a 404 Not Found.
This is the SAME endpoint doing this intermittently.
Here is my express app's code:
import bodyParer from "body-parser";
import methodOverride from "method-override";
import helmet from "helmet";
import fileUpload from "express-fileupload";
import cors from "cors";
import { errors } from "celebrate";
import { expressRouter } from "./routes";
import config from "../config/config";
import { ErrorHandlers } from "../middleware";
const expressApp = express();
expressApp.use(bodyParer.json());
expressApp.use(methodOverride());
expressApp.use(helmet());
expressApp.use(fileUpload());
expressApp.use(cors());
expressApp.use(errors());
expressApp.use(config.api.v1Prefix, expressRouter);
const errorHandlers = new ErrorHandlers();
expressApp.use(errorHandlers.notFound);
expressApp.use(errorHandlers.handler);
export { expressApp };
This is what the router looks like:
// import user from "../routes/user";
const expressRouter = Router();
expressRouter.get("/status", (req, res) => res.send("OK"));
// user(expressRouter); // TODO: finish this off when above '/status' works...
export { expressRouter };
I also suspect the error handlers we have, and this is what they look like:
import { inversifyContainer } from "../config/inversify_config";
import { TYPES } from "../config/inversify_types";
import { Logger } from "../loaders/logger";
import httpStatus from "http-status";
export class ErrorHandlers {
loggerDependency = inversifyContainer.get<Logger>(TYPES.LoggerDependency);
notFound(req, res, next) {
const error = new Error("Not Found");
error["status"] = 404;
next(error);
}
public handler(err, req, res, next) {
const response = {
code: err.status,
message: err.message || httpStatus[err.status],
errors: err.errors,
stack: err.stack,
};
if (process.env.NODE_ENV !== "development") {
delete response.stack;
}
res.status(err.status);
res.json(response);
}
}
Has anyone else experienced this before?
Please let me know if there is anything else I can provide for assistance.
Up to now I have not been able to identify the issue. Any help will be greatly appreciated!
So... ehmmm.
We are using cloud foundry (in IBM).
What happened was that, in the past, our continuous deployment got stuck. Then we manually cancelled that deployment, so that the queued-up deployments could run and proceed at the time :)
What I realised today was that the OLD app never got deleted. This was a cloud foundry service that was running on the same domain (url) as the active cloud foundry service, which effectively made it 2 running instances, in other words.
The OLD service obviously did not have this new endpoint and it never would, as it was detached from the deployment.
Once I deleted the old service, this issue completely disappeared.
Thanks for anyone that took the time to read through all this nonense. Cheers!
I will just say first of all that I am aware of almost all the questions asked on this site under this title.
The solutions there were pretty obvious and already done by me (with no success) or only helped for those specific cases and didn’t really work in my case unfortunately.
Now, for the problem:
I'm trying to create a route that will handle a get request and a post request which are sent to the route 'ellipses'.
These requests should receive and send data from and to an SQL database.
The problem is that for some reason the router is not ready to get these functions and gives me the error in the title:
Router.use () requires middleware function but got an undefined
Here is my code:
This code is from the file dat.js. its porpose is just to access the SQL database.
import { Sequelize } from "sequelize";
export const sequelize = new Sequelize('TheDataBaseName', 'TheUser', 'ThePassword', {
host: 'localhost',
dialect: 'mssql'
});
This code is from the file: controller.js. its porpose is to manage the requests and load the data.
import { sequelize } from "../dat";
export const sendEllipses = async (req, res, next) => {
try {
const ellipses = await getEllipsesFromJson();
return res.send(ellipses);
} catch (e) {
console.log(e);
}
};
export const addNewEllipse = async (req, res, next) => {
const { body: obj } = req;
let newEllipse;
try {
if (Object.keys(obj) !== null) {
logger.info(obj);
newEllipse = await sequelize.query(
`INSERT INTO [armageddon].[dbo].[ellipses] (${Object.keys(
obj
).toString()})
values (${Object.values(obj).toString()})`
);
} else {
console.log("the values are null or are empty");
}
return res.send(newEllipse);
} catch (error) {
console.log(error);
}
};
This code is on the file: routers.js.
its porpose is to define the route
import Router from "express";
import { sendEllipses } from "../ellipses.controller";
import { addNewEllipse } from "../ellipses.controller";
const router = Router();
export default router.route("/ellipses").get(sendEllipses).post(addNewEllipse);
This code is from the file: app.js. This is where everything actually happens.
import { router } from "../routers";
import express from "express";
app.use('/api', router);
app.listen(5000, () => {
console.log("server is runing on port 5000")
});
You need to export the router
const router = Router();
router.route("/ellipses").get(sendEllipses).post(addNewEllipse)
export default router
Now import the router:
import routes from "../router.js";
app.use('/api', routes);
Its also mentioned in the docs: https://expressjs.com/de/guide/routing.html#express-router
I'm trying to create a routing function for some products. The home screen works fine (displaying all the products), but I'm trying to add functionality so that when a user clicks on the product it automatically redirects to a page which pulls information about that products.
When I run my back end server (npm start) I get this in my terminal and an undefined response when I click on my product:
[nodemon] 2.0.12
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): backend/**/*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `babel-node backend/server.js`
serve at http://localhost:5000 [Function (anonymous)]
I've tried going through my code a few times and playing around with things to see if there's an issue with a function but couldn't see an issue.
This is the code for my server.js:
import express from 'express';
import cors from 'cors';
import { products } from './data.js';
const app = express();
app.use(cors());
app.get('/api/products', (_req, res) => {
res.send(products);
});
app.get('/api/products/:id')
app.listen(5000, () => {
console.log('serve at http://localhost:5000', (req, res) => {
const product = data.products.find((x) => x._id === req.params.id)
if (product) {
res.send(product);
} else {
res.status(404).send({ message: 'Product Not Found' })
}
})
});
This is my config.js:
import axios from 'axios'
import { apiUrl } from "./config"
export const getProduct = async (id) => {
try {
const response = await axios({
url: `${apiUrl}/api/products/${id}`,
method: 'GET',
headers: {
'Content-Type': 'application/json',
}
});
if (response.statusText !== 'OK') {
throw new Error(response.data.message);
}
return response.data;
} catch (err) {
console.log(err);
return { error: err.message }
}
};
I've just included my util.js and the product screen code below just for a better understanding of what I'm doing, however I think the issue would be in the server.js or config.js.
util.js:
export const parseRequestUrl = () => {
const url = document.location.hash.toLowerCase();
const request = url.split('/');
return {
resource: request[1],
id: request[2],
action: [3],
};
}
productscreen.js
import { getProduct } from '../api';
import { parseRequestUrl } from '../util'
const ProductScreen = {
render: async () => {
const request = parseRequestUrl();
const product = await getProduct(request.id);
return `<h1>${product.name}</h1>`;
}
}
export default ProductScreen;
You are literally printing the function with console.log by providing it as a second argument. Move the handler function to the appropriate route handler for /api/products/:id, as shown below:
import express from 'express';
import cors from 'cors';
import { products } from './data.js';
const app = express();
app.use(cors());
app.get('/api/products', (_req, res) => {
res.send(products);
});
// The handler function is moved here from `listen` callback.
app.get('/api/products/:id', (req, res) => {
const product = data.products.find((x) => x._id === req.params.id);
if (product) {
res.send(product);
} else {
res.status(404).send({ message: 'Product Not Found' });
}
})
app.listen(5000, () => {
console.log('serve at http://localhost:5000');
});
I have been trying to make socket.io work with my Nodejs and Typescript backend and React + JSX frontend, this is my first experience with socket.io but it has been a nightmare.
This is the server.ts file
import Express, {Application} from 'express';
import dotenv from 'dotenv';
const app: Application = Express();
import http from 'http';
//getting the Socket Type from socket io
import {Socket} from 'socket.io';
//importing the IO object form seperate file
import {init, socket} from './utils/socketio'; // <--- seperate socketio.ts file
import teacher_route from './Routes/teacher';
import student_route from './Routes/student';
import cookie_check_route from './Routes/cookieCheck';
import bodyParser from "body-parser";
import cors from 'cors';
import cookieParser from "cookie-parser";
const server = http.createServer(app);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
dotenv.config();
app.use(cors({
origin: "http://localhost:3000",
credentials: true,
}));
//initializing the io
init(server);
app.use(cookieParser());
app.use('/t', teacher_route);
app.use('/s', student_route);
app.use('/c', cookie_check_route);
//connecting the io
socket().on("connection", (socket: Socket)=> {
console.log("reached server")
socket.on("joined", (data: object)=> {
console.log("reached joined")
//#ts-ignore
socket.emit("joined2", {
//#ts-ignore
full_name: "student[0].full_name",
attendance: "",
average_score: "",
average_attendance: ""
})
})
})
server.listen(process.env.PORT);
SocketIO.ts file on the backend
import socketIo, {Socket} from 'socket.io';
let io: any;
//#ts-ignore
const init = (httpServer)=>{
//#ts-ignore
io = socketIo(httpServer, {
cors: true,
origins: ["http://127.0.0.1:3000"]
});
return io;
}
const getIO = () => {
if(!io){
throw new Error("Socket.io is not initialised!");
}
return io;
}
const socket = () => {
return getIO().on("connection", (socket: Socket)=> {
// console.log("inside socketio.ts file")
return socket;
})
}
export {init, getIO, socket};
This is the useEffect hook in StudentPortal.jsx file
useEffect(()=> {
setLoader(true)
socket.emit("joined"); // <--- emmiting an event
axios.get(`${config.apiEndpoint}/s/checkclasses`, {
withCredentials: true
}).then(response => {
setClasses(true);
setDisableSubmit(false);
setLoader(false)
if(response.data.class_data_array){
setClassData(response.data.class_data_array.reverse());
}
});
}, [addedClass])
And Finally this is the Class.jsx file where i want to finally get that event
socket.on("joined2", (data)=> {
// setClassData([...classData, data]);
console.log("Class.jsx socket");
})
So the gist of this is that i am emmitting an event from StudentPortal.jsx named joined and listening for it in the Server.ts and in it's body, i am emmitting another event named Joined2 and listening for it in the Class.jsx, i have tried many many different things, placed socket connection in different files, tried to connect first and then emmit, and so much more, nothing seems to work.
Any help is truly appreciated.
Thank you