I have problem with post request authentification while trying to run the code I get error invalide request does anyone know how I could solve this problem, I get this error { error: 'invalid_request' }
const express = require('express');
const fetch = require('node-fetch');
const btoa = require('btoa');
const { catchAsync } = require('./utils');
const router = express.Router();
const CLIENT_ID = 'CLIENT_ID ';
const CLIENT_SECRET = 'CLIENT_SECRET';
const creds = btoa(`${CLIENT_ID}:${CLIENT_SECRET}`);
const redirect = encodeURIComponent('http://localhost:50451/callback');
router.get('/login', (req, res) => {
res.redirect('https://flow.polar.com/oauth2/authorization?response_type=code&client_id=client_id');
});
router.get('/list', catchAsync(async (req, res) => {
if (!req.query.code) throw new Error('NoCodeProvided');
const code = req.query.code;
const creds = btoa(`${CLIENT_ID}:${CLIENT_SECRET}`);
fetch('https://polarremote.com/v2/oauth2/token', {
method: 'POST',
data : {
'grant_type' : 'authorization_code',
'redirect_uri' : redirect,
'code' : code
},
headers : {
'Authorization':`Basic ${creds}`,
'Content-Type':'application/x-www-form-urlencoded',
'Accept':' application/json;charset=UTF-8'
}
})
.then(function(response) {
return response.json();
console.log(response.json());
}).then(function(body) {
console.log(body);
res.send('POST');
});
})
Related
So i am trying to create a discord bot dashboard and I am including a Discord Oauth2 to get User information. My Discord Oauth2 works, however after authorising, it redirects me to the homepage but the URL has token=undefined . The console does log "It works!". How do I fix the undefined access token?
http://localhost:3000/?token=undefined
var path = require('path');
const express = require('express');
const fetch = require('node-fetch');
const app = express();
require('dotenv').config();
const btoa = require('btoa');
const { catchAsync } = require('./utils.js')
const CLIENT_ID = process.env.CLIENT_ID;
const CLIENT_SECRET = process.env.CLIENT_SECRET;
const redirect = encodeURIComponent('http://localhost:3000/callback');
...
app.get('/login', (req, res) => {
res.redirect(`https://discord.com/api/oauth2/authorize?client_id=${CLIENT_ID}&redirect_uri=${redirect}&response_type=code&scope=identify%20email%20guilds`);
});
app.get('/callback', catchAsync(async (req, res) => {
if (!req.query.code) throw new Error('NoCodeProvided');
const code = req.query.code;
const creds = btoa(`${CLIENT_ID}:${CLIENT_SECRET}`);
const response = await fetch(`https://discordapp.com/api/oauth2/token?grant_type=authorization_code&code=${code}&redirect_uri=${redirect}`,
{
method: 'POST',
headers: {
Authorization: `Basic ${creds}`,
},
});
const json = await response.json();
console.log("it works!")
res.redirect(`/?token=${json.access_token}`);
}));
app.listen(3000)
There seemed to be a problem with how the callback link was set up, So I changed it to look like this and it works.
app.get('/callback', catchAsync(async (req, res) => {
const data = {
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
grant_type: 'authorization_code',
redirect_uri: redirect,
code: req.query.code,
scope: ['identify', 'email', 'guilds'],
};
const response = await fetch('https://discord.com/api/oauth2/token', {
method: 'POST',
body: new URLSearchParams(data),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
})
const json = await response.json();
const fetchDiscordUserInfo = await fetch('http://discordapp.com/api/users/#me', {
headers: {
Authorization: `Bearer ${json.access_token}`,
}
});
const userInfo = await fetchDiscordUserInfo.json();
res.redirect('http://localhost:3000/dashboard')
console.log(userInfo);
I am new to Nodejs and am trying to figure out why I cannot pass the returned value of my function into my function when I call it. Here is my code:
const SpotifyWebApi = require('spotify-web-api-node');
const http = require("http");
const request = require('request');
const querystring = require('querystring');
const { post } = require('request');
const express = require('express');
const { response } = require('express');
const https = require('follow-redirects').https;
//sets express server vars
const app = express()
const port = 8080
app.get('/', (req, res) => {
res.send('Server Connected')
})
app.listen(port, () => {
console.log(`Now serving on ${port} at ${process.env.URI} `)
})
require('dotenv').config();
//authenticate to SpotifyAPI
var spotifyApi = new SpotifyWebApi({
clientId: process.env.CLIENT_ID,
clientSecret: process.env.SECRET_ID,
redirectUri: process.env.URI,
});
const scope = 'user-read-private user-read-email ';
const authUrl = 'https://accounts.spotify.com/api/token?grant_type=client_credentials';
//Headers needed to auth to SpotifyAPI for Bearer token
const tokenHeaders = {
'Authorization': process.env.ACCESSTOKEN,
'Content-Type': 'application/x-www-form-urlencoded',
};
//spotify Auth Payload
const options = {
'method': 'POST',
'url': authUrl,
'headers': tokenHeaders
};
function accessTokenAuth(bearerToken){
request(options, (error, response) => {
if (error) throw new Error(error);
const accessTokenBody = response.body;
// console.log(accessTokenBody)
// console.log(request)
const obj = JSON.parse(accessTokenBody);
const bearerToken = ("Bearer " + obj.access_token); //add this bearerAuth part to a function to make it repeatable. Times out in 3600???
// console.log(bearerToken);
return bearerToken;
});
}
//Add first playlists request using the bearer token
accessTokenAuth(bearerToken);
In the function "accessTokenAuth" I create a series of calls that essentially posts data from the above dictionaries into a function that then sends the data to the URL to receive a token back. My question is this, at the bottom of the function when I return "bearerToken", how come I cannot pass "bearerToken" into the function when I call it on line 67. Also, when I comment out calling the function and just run the program it prints out the "bearerToken" when I console.log it in the function. Why is this possible? Aren't you not able to access the function unless it is called?
Thank you!
I have the following reactjs code and using expressjs to handle the post request. req.body always returns {} from the app. But it works in Postman.
my reactjs code snippet:
handleSubmit(e) {
e.preventDefault();
fetch(config.urlDev + '/notes', {
method: 'post',
body: { "email":"test" },
//headers: {'Content-Type':'x-www-form-urlencoded'}
headers: {'Content-Type':'application/json'}
})
.then((res) => res.json())
.then((res) => {
console.log(res)
})
.catch((err) => {
console.log(err)
})
}
my expressjs code snippet:
module.exports = function (app, db) {
app.post('/notes', (req, res) => {
console.log(req.body)
console.log(req.params)
res.send(req.body)
})
}
server.js:
const express = require('express');
const MongoClient = require('mongodb').MongoClient
const bodyParser = require('body-parser')
const db = require('./config/db');
const app = express();
const port = 8000;
const cors = require('cors');
const path = require('path');
app.use(cors())
//app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended:true}))
MongoClient.connect(db.url, {useUnifiedTopology: true}, (err, database) => {
if (err) return console.log(err)
const mydb = database.db('notes')
require('./app/routes') (app, mydb);
app.listen(port, () => {
console.log ("server on " + port)
})
})
postman
Try un-commenting the line
//app.use(bodyParser.json()) and it should work.
or alternatively if you are sending headers in the fetch request as headers: {'Content-Type':'x-www-form-urlencoded'} instead of headers: {'Content-Type':'application/json'} it should work.
When i try to make a request to my server the client send two requests, the first with an empty body, and the second with the correct body
this is my server file
const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
const cors = require('cors');
const bodyParser = require('body-parser');
const authMiddleware = require('./app/middlewares/auth.middleware');
const db = require('./config/db');
app.use(authMiddleware);
app.use(cors({ origin: '*' }));
app.use(bodyParser.json());
db.then(res => {
require('./app/routes')(app);
});
server.listen(3210, () => {
console.log('\x1b[0m', 'Backend escutando e enviando na porta 3210');
});
this is the route file
const userController = require('../controllers/user.controller');
module.exports = app => {
app.post('/sign-up', async (req, res) => {
try {
const signUpData = await userController.signUp(req.body);
res.status(200).json(signUpData.user);
} catch (error) {
console.log(error);
res.status(400).json(error);
}
});
app.post('/sign-in', async (req, res) => {
try {
const signInData = await userController.signIn(req.body);
res.header('x-auth-token', signInData.token);
res.status(200).json(signInData);
} catch (error) {
console.log(error);
res.status(400).json(error);
}
});
};
here is my axios configuration on my react project
import axios from 'axios';
export const apiUrl = 'http://localhost:3210';
export const api = axios.create({
baseURL: apiUrl,
headers: {
common: {
'Content-Type': 'application/json'
}
}
});
the function where i do the request
export const signIn = data => {
return api
.post(`/sign-in`, data)
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
});
};
This error only occours when the request is made via client, when i
use postman everything works fine
I try to deploy a web app. But i got a problem using a chat in my web site. It's work perfectly fine in local but not online. I got a response 401 "Unauthorized" when i try to access to my chat. I use socket.io
Here is the code :
Index.js
const express = require('express');
const bodyparser = require('body-parser');
const security = require('./middleware/security');
const userRouter = require('./routes/user');
const AnnonceRouter = require('./routes/annonce');
const securityRouter = require('./routes/security');
const commentRouter = require('./routes/comment');
const mailRouter = require('./routes/mail')
const path = require('path');
const isDev = process.env.NODE_ENV !== 'production';
const PORT = process.env.PORT || 5000;
const app = express();
const cors = require('cors');
var chat = require('https').createServer(app)
var io = module.exports.io = require('socket.io').listen(chat)
const SocketManager = require('./SocketManager')
io.on('connection', SocketManager)
if (process.env.NODE_ENV === 'production') {
app.use(express.static('../client/build')); // serve the static react app
app.use(cors());
app.use(bodyparser.json());
app.use(security.verifyToken);
app.use('/', securityRouter);
app.use('/annonce', AnnonceRouter);
app.use('/user', userRouter);
app.use('/comment', commentRouter);
app.use('/mail', mailRouter);
app.get(/^\/(?!api).*/, (req, res) => { // don't serve api routes to react app
res.sendFile(path.join(__dirname, '../client/build/index.html'));
})
console.log('Serving React App...');
};
app.listen(PORT, function () {
console.error(`Node ${isDev ? 'dev server' : 'cluster worker '+process.pid}: listening on port ${PORT}`);
});
a part of my layout.js
import React, { Component } from 'react';
import io from 'socket.io-client'
import { USER_CONNECTED, LOGOUT } from '../Events'
import LoginForm from './LoginForm'
import ChatContainer from './chats/ChatContainer'
const socketUrl = "https://teachonline.herokuapp.com"
export default class Layout extends React.Component {
constructor(props) {
super(props);
this.state = {
socket:null,
user:null
};
}
componentWillMount() {
this.initSocket()
}
/*
* Connect to and initializes the socket.
*/
initSocket = ()=>{
const socket = io(socketUrl)
socket.on('connect', ()=>{
console.log("Chat Connected");
})
this.setState({socket})
}
When i try to access to my chat here is the logs in Heroku
2019-08-26T22:25:04.828537+00:00 app[web.1]: TypeError: Cannot read property 'replace' of undefined
2019-08-26T22:25:04.828550+00:00 app[web.1]: at verifyToken (/app/server/middleware/security.js:13:29)
Here is my security.js
const verifyJWTToken = require('../libs/auth').verifyToken;
const access_routes = ["/login_check", "/user", "/mail/send", "/landing-page", "/security/login", "/chat","/socket.io"]
const verifyToken = (req, res, next) => {
if(access_routes.indexOf(req.path) > -1) {
next();
} else {
const auth = req.get('Authorization');
if(!auth || !auth.startsWith('Bearer ')) {
res.sendStatus(401);
}
verifyJWTToken(auth.replace("Bearer ", ""))
.then((decodedToken) => {
req.user = decodedToken;
next();
})
.catch((error) => res.status(400).send({
error: "JWT TOKEN invalid",
details: error
}));
}
}
module.exports = {
verifyToken
}
if it's needed the auth.js
const jwt = require('jsonwebtoken');
const JWT_SECRET = "MaBelleJonquille";
const createToken = function (user = {}) {
return jwt.sign({
payload: {
userName: user.user_name
}
}, JWT_SECRET, {
expiresIn: "7d",
algorithm: "HS256"
});
};
const verifyToken = function (token) {
return new Promise((resolve, reject) => jwt.verify(token, JWT_SECRET, (err, decodedToken) => {
if(err || !decodedToken) {
reject(err);
}
resolve(decodedToken);
}));
};
//fonction pour hasher le password rentré
module.exports = {
createToken,
verifyToken
}
The example of a request
let myHeaders = new Headers();
myHeaders.append("Content-type", "application/json");
myHeaders.append("Authorization", "Bearer "+localStorage.getItem('tokenJWT'));
fetch (URL + localStorage.getItem('user_name'),
{
method:'GET',
mode: "cors",
headers : myHeaders
})
.then(response => response.json())
.then(data => {
data.user_skill.map(x => {
this.skill.push({label: x, value: x});
});
})
.catch(error => (error));
I tried severals things found in the internet but none of them worked for me, so if you have any idea of what am i doing wrong, i'm listening.
Thanks for reading me