Have problem with Node Js backend, if i use test client (not React) it works, if place it to React app I have subj error.
Server is running on http://localhost:8000
undefined:1
SyntaxError: Unexpected end of JSON input
at JSON.parse ()
at Server.requestListener (/home/boris/bookni_ru_srv/backend.js:27:38)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
Here is server part:
let { Logincheck } = require('./ConnectDB');
const http = require("http");
var fs = require('fs');
const host = 'localhost';
const port = 8000;
const rbkp_srv ='192.168.56.101';
const test = fs.readFileSync('test.json', 'utf-8');
const requestListener = async function (req, res) {
const buffers = [];
for await (const chunk of req) {
buffers.push(chunk);
}
const data = Buffer.concat(buffers);
res.setHeader("Content-Type", "application/json");
switch (req.url) {
case "/login":
res.writeHead(200);
const rbkp_passwd = JSON.parse(data).passwd;
const rbkp_user = JSON.parse(data).user;
let login = Logincheck(rbkp_srv, rbkp_user, rbkp_passwd);
login.then(function(result){if (result===true) {console.log('Login sucessed'); res.end('Login');} else { console.log(result); res.end(result.toString())}
});
break
}
};
const server = http.createServer(requestListener);
server.listen(port, host, () => {
console.log(`Server is running on http://${host}:${port}`);
});
Here is FrontEnd part:
export default function Auth(){
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({"user" : "boris",
"passwd" : "test"})
};
fetch('http://localhost:8000/login', requestOptions)
.then(response => response.json())
.then(data => this.setState({ postId: data.id }));
}`
Have no clu hoe to fix it yet need help.
This code is for an express website for my discord bot I need it to catch the mutual guilds but it's giving this error:
TypeError: botGuilds.find is not a function
at C:\Users\não te interessa\Desktop\projetos\bot\backend\utils\utils.js:3:56
at Array.filter (<anonymous>)
at Proxy.methods.<computed> (C:\Users\não te interessa\Desktop\projetos\bot\backend\node_modules\mongoose\lib\types\array\methods\index.js:956:24)
at getMutualGuilds (C:\Users\não te interessa\Desktop\projetos\bot\backend\utils\utils.js:3:28)
at C:\Users\não te interessa\Desktop\projetos\bot\backend\routes\discord.js:11:28
at processTicksAndRejections (node:internal/process/task_queues:96:5)
which uses getMutualGuilds:
const router = require("express").Router()
const { getBotGuilds } = require("../utils/api")
const { getMutualGuilds } = require("../utils/utils")
const User = require('../database/schemas/Users')
router.get('/guilds', async (req, res) => {
const guilds = await getBotGuilds();
const user = await User.findOne({ discordId: req.user.discordId });
if (user) {
const userGuilds = user.get('guilds');
const mutualguilds = await getMutualGuilds(userGuilds, guilds);
res.send(mutualguilds);
}
});
module.exports = router
getMutualGuilds code:
function getMutualGuilds(userGuilds, botGuilds) {
return userGuilds.filter((guild) => botGuilds.find((botGuild) => (botGuild.id === guild.id) && (guild.permissions & 0x20) === 0x20))
}
module.exports = { getMutualGuilds }
code of botGuilds:
const fetch = require("node-fetch")
const TOKEN = "token of my bot";
async function getBotGuilds() {
const response = await fetch('http://discord.com/api/v8/users/#me/guilds', {
method: 'GET',
headers:{
Authorization: `Bot ${TOKEN}`
}
})
return response.json()
}
module.exports = { getBotGuilds }
I am getting this error:
Unexpected empty object pattern no-empty-pattern
in this code
const Login = () => {
const[{} ,dispatch] = useStateValue()
const signIn = () => {
auth.signInWithPopup(provider)
.then(result => {
dispatch({
type: actionTypes.SET_USER,
user: result.user
})
})
.catch(error => alert(error.message))
}
I don't know what useStateValue is supposed to do, but this line doesn't parse:
const[{} ,dispatch] = useStateValue()
perhaps you meant:
const [value, dispatch] = useStateValue({})
I am using nodejs koa rest api service. And I want to pass a parameter to validation middleware.
But I also need to pass context.
How can I correctly use middlewares with koa2
//route.js
const Router = require('koa-router')
const auth = require('../middlewares/auth')
const controller = require('../controllers').editorsController
const schemas = require('../schemas/joi_schemas')
const validation = require('../middlewares/validation')
const router = new Router()
const BASE_URL = `/editors`
router.get('/protected', auth, controller.protected)
router.get(BASE_URL, controller.getEditors)
router.post(BASE_URL, auth, validation(schemas.editorPOST, 'body'), controller.addEditor)
module.exports = router.routes()
//validation.js
const Joi = require('joi')
module.exports = (schema, property, ctx, next) => {
const { error } = Joi.validate(ctx.request[property], schema)
console.log(error)
const valid = error == null
if (valid) {
next()
} else {
const { details } = error
const message = details.map(i => i.message).join(',')
ctx.status = 422
ctx.body = {
status: 'error',
message: message
}
}
}
//joi_schemas.js
const Joi = require('joi')
const schemas = {
editorPOST: Joi.object().keys({
username: Joi.string().required(),
password: Joi.string().required(),
enable: Joi.number()
})
}
module.exports = schemas
I get some errors:
Cannot read property 'request' of undefined
Or any other solutions?
ctx.request is undefined because ctx wasn't passed as an argument:
validation(schemas.editorPOST, 'body')
And ctx it's unavailable in the scope where the middleware was called.
If a middleware needs to be parametrized, it should be higher order function:
module.exports = (schema, property) => (ctx, next) => {
...
I am making a request to endpoint written in koa.js and I am new to this framework.
API return 404 response.
Route file looks like below:
const collabRepo = require("../repo/collab/collab-repo")
const notificationRepo = require("../repo/collab/notification-repo")
const rest = require("restling")
const jwt = require("jsonwebtoken")
const CONFIG = require("config")
const SECRET = CONFIG.get("auth.jwt.secret")
const JWT_COOKIE_NAME = CONFIG.get("auth.jwt.cookie.name")
const TOKENTIME = CONFIG.get("auth.jwt.ttl")
const FEED_API_BASE = CONFIG.get("urls.activityFeedApi")
const FEED_API_VERSION = "v1"
const FEED_API = FEED_API_BASE + "/" + FEED_API_VERSION
const logger = require("winston")
const { jwtAuth } = require("../auth")
const PROTECTED_ROUTES = [
"/collab/follow",
"/collab/unfollow",
"/collab/follower/list",
"/collab/follower/public/list",
"/collab/following/list",
"/collab/following/public/list",
"/collab/following/count",
"/collab/following",
"/collab/notify",
"/collab/discover/people",
"/collab/discover/expression"
]
async function followFeed(toFollowId, userObject, follow) {
const args = {
data: {
follow: {
class: "user",
id: toFollowId
}
},
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Cookie": JWT_COOKIE_NAME + "=" + jwt.sign(userObject, SECRET, {
expiresIn: TOKENTIME
})
}
}
if (follow) {
return rest.post(FEED_API + '/follow', args)
}
return rest.post(FEED_API + '/unfollow', args)
}
when I log rest.post(FEED_API + '/follow', args) I get:
Promise { _bitField: 0, _fulfillmentHandler0: undefined,
_rejectionHandler0: undefined, _progressHandler0: undefined, _promise0: undefined, _receiver0: undefined, _settledValue: undefined } Unhandled rejection Error: Cannot POST
http://localhost/activity-feed/api/v1/follow
at Request. (\node_modules\restling\restling.js:26:21)
at Request.emit (events.js:180:13)
at Request._fireSuccess (\node_modules\restler\lib\restler.js:223:12)
at \node_modules\restler\lib\restler.js:161:20
at IncomingMessage.auto (\node_modules\restler\lib\restler.js:402:7)
at Request._encode (\node_modules\restler\lib\restler.js:198:29)
at \node_modules\restler\lib\restler.js:157:16
at Request._decode (\node_modules\restler\lib\restler.js:173:7)
at IncomingMessage. (\node_modules\restler\lib\restler.js:150:14)
at IncomingMessage.emit (events.js:185:15)
at endReadableNT (_stream_readable.js:1106:12)
at process._tickCallback (internal/process/next_tick.js:178:19)
module.exports = (router) => {
// Protect the marked routes
PROTECTED_ROUTES.forEach(url => {
router.use(url, jwtAuth)
})
// router.use("/collab", jwtAuth)
router.post("/collab/follow", async function (ctx) {
try {
const resp = await followFeed(ctx.request.body.followee_id, ctx.state.user, true)
return collabRepo.follow(ctx.state.user.id, ctx.request.body.followee_type, ctx.request.body.followee_id)
.then(data => {
ctx.body = {
data: data,
feed_data: resp.data
}
})
} catch (error) {
return error
}
}),
} // end of the module
I have removed extra code which is not relevant to this question.
Functions called within route:
Function followFeed
async function followFeed(toFollowId, userObject, follow) {
const args = {
data: {
follow: {
class: "user",
id: toFollowId
}
},
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Cookie": JWT_COOKIE_NAME + "=" + jwt.sign(userObject, SECRET, {
expiresIn: TOKENTIME
})
}
}
if (follow) {
return rest.post(FEED_API + '/follow', args)
}
return rest.post(FEED_API + '/unfollow', args)
}
Function follow
follow: function(user_id, followee_type, followee_id) {
return db("follower").returning("followee_id").insert({ "user_id": user_id, "followee_id": followee_id, "followee_type": followee_type })
.then(data => {
return data[0]
})
},
Can someone help me and tell me what is wrong with my code?
I am signed in and session has JWT, route exist then why I am getting 404?
What is wrong with code at backend?
In browser console I get:
Error: Uncaught (in promise): Response with status: 404 Not Found for
URL
This is what I get when I print console.log(rest.post(FEED_API + '/follow', args))
Promise {
_bitField: 0,
_fulfillmentHandler0: undefined,
_rejectionHandler0: undefined,
_progressHandler0: undefined,
_promise0: undefined,
_receiver0: undefined,
_settledValue: undefined }
Unhandled rejection Error: Cannot POST http://localhost/activity-feed/api/v1/follow
at Request.<anonymous> (projectpath\node_modules\restling\restling.js:26:21)
Update
Below is activity feed route:
router.post("/v1/follow", function(ctx) {
const user = ctx.state.user
const request = ctx.request.body
return feedRepo.followUserFeed(user.id, request.follow)
.then(result => {
ctx.body = result
})
.catch(error => {
ctx.error = error
})
})
Function called inside this route
followUserFeed: async function(id, feed) {
const userFeed = new GSFlatFeed(LOOKUP.FEEDS.USER, id)
const feedToFollow = new GSFlatFeed(feed.class, feed.id)
const res = await StreamProvider.followFeed(userFeed, feedToFollow)
return res
},
app.js of activity-feed/api
const Koa = require("koa")
const Router = require("koa-router")
const body = require("koa-body")
const cors = require("kcors")
const passport = require("koa-passport")
const logger = require("winston")
var JwtStrategy = require("passport-jwt").Strategy
const CONFIG = require("config")
const SECRET = CONFIG.get("auth.jwt.secret")
const JWT_COOKIE_NAME = CONFIG.get("auth.jwt.cookie.name")
const allRoutes = require("./server/routes/all-routes")
const app = new Koa()
const router = new Router()
const jwtAuth = passport.authenticate(["jwt"], { session: false })
passport.use(new JwtStrategy({
secretOrKey: SECRET,
jwtFromRequest: function(req) {
var token = null
if (req && req.cookies) {
token = req.cookies.get(JWT_COOKIE_NAME)
}
return token
}
},
function(jwt_payload, done) {
done(null, jwt_payload)
}))
router.use("/v1/*", jwtAuth)
allRoutes(router)
app.use(async(ctx, next) => {
try {
await next()
} catch (err) {
logger.error(err)
ctx.throw(err.status || 500, err.message)
}
})
app.use(cors())
app.use(passport.initialize())
app.use(body())
app
.use(router.routes())
.use(router.allowedMethods())
module.exports = app
Any help would be highly appreciated!
While registering the routes you have missed the FEED_API (base url).
PROTECTED_ROUTES.forEach(url => {
router.use(url, jwtAuth)
})
So your url actually looks like http://localhost/collab/follow instead of http://localhost/activity-feed/api/v1/follow
Instead, you should register your routes like,
// Protect the marked routes
module.exports = (router) => {
// Protect the marked routes
PROTECTED_ROUTES.forEach(url => {
router.use(FEED_API + url, jwtAuth)
})
// router.use("/collab", jwtAuth)
router.post(FEED_API + "/collab/follow", async function (ctx) {
Now you can POST to /collab/follow as http://localhost/activity-feed/api/v1/collab/follow