I make simple instagram api application and I have problem with my routes, export and import. i get error TypeError: Router.use() requires a middleware function but got a undefined
at Function.use (C:\Documents\Desktop\digi.me\node_modules\express\lib\router\index.js:458:13)
at Object. (C:\Documents\Desktop\digi.me\lib\routes\routes.js:12:8)
I have two routes userRouter that go on localhost:3000
and mediaRouter that go on localhost:3000/media
my userRouter.ts
import request, { post } from "request"
import express from "express"
import { Router } from 'express';
const app = express()
const token: any = process.env.INSTAGRAM_TOKEN
export const userRouter = Router()
userRouter.get("/", (req: any, res: any) => {
const url = 'https://graph.instagram.com/17841403377847296/?access_token='+token+'&fields=account_type,media_count,username'
request({ url: url, json: true }, (error: string, response: any) => {
if(error){
res.send("unable to connect to service")
}else{
res.send("USER " + response.body.username + " HAVE " + response.body.media_count + " POSTS")
}
})
})
my mediaRouter
import request, { post } from "request"
import express from "express"
import {Post} from "../models/Post"
import { Router } from 'express';
const token: any = process.env.INSTAGRAM_TOKEN
export const mediaRouter = Router()
mediaRouter.get("/media", (req: any, res: any) => {
console.log(0);
const url = 'https://graph.instagram.com/17841403377847296/media?fields=id,media_url,timestamp&access_token='+token+''
request({ url: url, json: true }, (error:string, response: any) => {
if(error){
console.log('error');
res.send("unable to connect to service")
} else {
const array = response.body.data
var Posts: Post[] = [];
array.forEach(function (obj: any) {
Posts.push(new Post(obj.media_url, obj.timestamp))
});
res.send(Posts);
}
})
})
my routes.ts
import { Router } from 'express';
import userRouter from "./routes"
import mediaRouter from "./routes"
import express from 'express';
const app = express();
const routes = Router();
routes.use('/', userRouter);
routes.use('/media', mediaRouter);
export default routes
and my main app.ts
import express from "express"
import * as dotenv from "dotenv"
import routes from "./routes/routes"
const app = express()
dotenv.config();
//envirements variable for port
const port: any = process.env.PORT
app.use(routes);
app.use(express.json());
//Adding server to port
app.listen(port, () => {
console.log("server is listen on port 3000")
})
Related
socket.request.user from isLoggedInSocket is undefined. For the client, I have also tried connecting with ws://127.0.0.1:5000. I am using Google oauth2 for passport js. My express endpoints successfully have the user session details. Once I comment out isLoggedInSocket, I can connect to the socket.
Does anyone have any insight on what I can do to get the session onto socket.io?
Server:
import express, { Application } from 'express';
import http from 'http';
import { Server } from 'socket.io';
import passport from 'passport';
import cookieSesson from 'cookie-session';
import cors from 'cors';
import fishingSocket from './sockets/fishing';
import authRouter from './routers/authentication';
import setupAuth from './authSetup';
import { isLoggedIn, isLoggedInSocket } from './middleware';
const corsConfig: any = {
cors: {
origin: ['http://127.0.0.1:3000'],
credentials: true,
},
};
const app: Application = express();
app.use(
cors({
origin: ['http://127.0.0.1:3000'],
credentials: true,
})
);
const session = cookieSesson({
name: 'pond-session',
keys: ['key1', 'key2'],
});
app.use(session);
app.use(passport.initialize());
app.use(passport.session());
setupAuth();
const server = http.createServer(app);
const io = new Server(server, corsConfig);
const wrap = (middleware: any) => (socket: any, next: any) =>
middleware(socket.request, {}, next);
io.use(wrap(session));
io.use(wrap(passport.initialize()));
io.use(wrap(passport.session()));
const isLoggedInSocket = (socket: any, next: any) => {
if (socket.request.user) {
next();
} else {
console.log('No auth in socket');
next(new Error('unauthorized'));
}
};
io.use(isLoggedInSocket);
fishingSocket(io);
app.use('/auth', authRouter);
server.listen(5000, () => console.log('Server Running'));
Client:
socket = io('http://127.0.0.1:5000', {
withCredentials: true
})
ReactJS code
import axios from 'axios';
import {useEffect,useState} from 'react';
import ReactDOM from "react-dom/client";
import React from "react";
const App = () => {
const [res,setRes] = useState(null)
useEffect(() => {
document.cookie='hello=3';
axios.post('http://localhost:4000/hello').then(res1 => {
setRes(res1.data)
})
},[])
return (
<div>
{res}
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
Nodejs code
import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser'
import cookieParser from 'cookie-parser'
const PORT = 4000;
const app = express();
// cors
app.use(cors());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser())
app.post('/hello', (req, res) => {
console.log(req.cookies)
res.send('This is from server!')
})
app.listen(PORT, () => {
console.log('listening on port', PORT); // eslint-disable-line no-console
});
On the line of console.log(req.cookies) in node.js it gives
[Object: null prototype] {}
what is the issue?
You are sending request to a different domain. If you want to send cookies with that request you would have to add withCredentials property in request options.
axios.get(
'http://localhost:4000/hello',
{ withCredentials: true }
);
I am trying to read all routes in my app.js file from './routes' folder,but
gettingerror:"TypeError: Cannot read property 'forEach' of undefined"
import express from "express";
import fs from "fs";
const app = express();
fs.readdir('./routes', (err, fs) => {
fs.forEach(file => {
app.use('/', require('./routes/' + file))
});
})
export default app
This worked for me:
sync
fs.readdirSync('/some/path/routes').forEach(function(file) {
app.use('/', require(`/some/path/routes/` + file));
});
async
fs.readdir('/some/path/routes', function(err, files){
files.forEach(function(file){
app.use('/', require(`/some/path/routes/` + file));
});
});
You can do using fs.readdirSync because the server is not yet started.
fs.readdir(`${__dirname}/routes`, (err, files) => {
if (err)
console.log(err);
else {
files.forEach(file => {
app.use('/', require(`${__dirname}/routes` + file));
})
}
})
You can use fspromise and import to handle using promise. 🚀🚀🚀
import { promises as fsPromises } from 'fs';
export const init = async () => {
const files = await fsPromises.readdir(`${__dirname}/routes`);
const router = Router();
const createRoute = async (file) => {
const route = await import(`./routes/${file}`);
router.use("/", route.default);
};
await Promise.all(files.map(createRoute));
return router;
}
// app.js
import {init} from "./routes";
const app = express();
(async() => {
await init();
// Start server
})();
I would suggest doing like below. You will have more control over routes. You can do customization on routes bases if needed.
ex. /v1 and /v2 etc..
// routes/index.js
import { Router } from "express";
import route1 from './route1';
import route2 from './route2';
const router = Router();
[route1, route2].forEach((route) => router.use("/", route));
export default router;
// app.js
import express from "express";
import routes from "./routes";
const app = express();
app.use("/", routes);
export default app;
I have an app that uses instagram api and has two route index "/" and media "/". Index is working fine but media doesn't work. It doesn't enter in get method. I made them in the same wa but one is working and the other doesn't.
I'm using typescript and node.
And I cant find the error.
My media route:
import request from "request"
import express from "express"
import { Router } from 'express'
import { Post } from "../models/Post"
const app = express()
const token: any = process.env.INSTAGRAM_TOKEN
const mediaRouter = Router()
mediaRouter.get("/media", (req: any, res: any) => {
const url = 'https://graph.instagram.com/17841403377847296/media?fields=id,media_url,timestamp&access_token='+token+''
request({ url: url, json: true }, (error: string, response: any) => {
if(error){
res.send("unable to connect to service")
}else{
const array = response.body.data
var Posts: Post[] = [];
array.forEach(function (obj: any) {
Posts.push(new Post(obj.media_url, obj.timestamp))
})
res.send(Posts);
}
})
})
export default mediaRouter
my user "/" rout (that work)
import request from "request"
import express from "express"
import { Router } from 'express'
const app = express()
const token: any = process.env.INSTAGRAM_TOKEN
const userRouter = Router()
userRouter.get("/", (req: any, res: any) => {
const url = 'https://graph.instagram.com/17841403377847296/?access_token='+ token +'&fields=account_type,media_count,username'
request({ url: url, json: true }, (error: string, response: any) => {
if(error){
res.send("unable to connect to service")
}else{
res.send("USER " + response.body.username + " HAVE " + response.body.media_count + " POSTS")
}
})
})
export default userRouter
and my main app.ts
import express from "express"
import dotenv from "dotenv"
import userRouter from "./routes/userRouter";
import mediaRouter from "./routes/mediaRouter";
const app = express()
dotenv.config();
//envirements variable for port
const port: any = process.env.PORT
app.use("/media", mediaRouter)
app.use("/", userRouter)
//Adding server to port
app.listen(3000, () => {
console.log("server is listen on port "+ port +"")
})
Remove the "/media" path from mediaRouter. Since its declared twice, the resulting path will be GET /media/media instead of GET /media:
mediaRouter.get("/", (req: any, res: any) => {})
i am making the webside , here is some of my code
in app.ts
import * as express from 'express';
import knex from './init/knex';
// Router
import indexRouter from './routers/index-router';
// Service
import gameService from './service/game-service';
const app = express();
var server = app.listen(8080, () => {
console.log('listen to 8080');
})
app.use('/', new indexRouter(new gameService(knex)).router());
in index-router.ts
import * as express from 'express';
export default class indexRouter {
private gameService: any;
constructor(gameService: any) {
this.gameService = gameService;
}
router() {
let router = express.Router();
router.get("/", this.get.bind(this));
router.post("/test", this.test.bind(this));
return router;
}
test(req: any, res: any) {
// console.log("indexRouter get()");
console.log(req.body);
res.render("gameboard", { pin: "1", username: "1", player: 1 });
}
get(req: any, res: any, next:any) {
req.body = {3:"3"};
// something i want to do here
}
}
When user link to "http://localhost:8080/" and "get" method is called
How can i change:
the url from "http://localhost:8080/" to "http://localhost:8080/test"
call "test" method with the new request body
I have spent a lot of time google how to do i but i can't find the best way to do the above two things.
Do you mean something like:
get(req: any, res: any, next:any) {
test(req.body);
res.redirect('/test');
}
?