I have faced CORS policy error .No 'Access-Control-Allow-Origin' header is present on the requested resource [duplicate] - javascript

This question already has answers here:
How to enable cors nodejs with express?
(10 answers)
Closed 10 months ago.
I have faced this problem so many time. I require all the middleware in my backend server code but it good for sometimes and then occur, after sometimes it's again running on his own and again cors policy error occur. Please give me a solution . Here is my backend code...
const express = require("express");
const { MongoClient, ServerApiVersion, ObjectId } = require("mongodb");
const cors = require("cors");
const jwt = require("jsonwebtoken");
const port = process.env.PORT || 5000;
require("dotenv").config();
const app = express();
//necessary middleware app.use(cors()); app.use(express.json());
function verifyJWT(req, res, next) {
const authHeader = req.headers.authorization;
if (!authHeader) {
return res.status(401).send({ message: "unauthorized access" });
}
const token = authHeader.split(" ")[1];
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
if (err) {
return res.status(403).send({ message: "Forbidden access" });
}
console.log("decoded", decoded);
req.decoded = decoded;
next();
});
}
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}#cluster0.nfrv0.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`;
console.log(uri);
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverApi: ServerApiVersion.v1,
});
async function run() {
try {
await client.connect();
const fruitCollection = client.db("fruitsInventory").collection("fruit");
//AUTH API
app.post("/login", async (req, res) => {
const user = req.body;
const accessToken = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, {
expiresIn: "1d",
});
res.send({ accessToken });
});
//get data
app.get("/inventory", async (req, res) => {
const query = {};
const cursor = fruitCollection.find(query);
const result = await cursor.toArray();
res.send(result);
});
//get inventory id
app.get("/inventory/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: ObjectId(id) };
const result = await fruitCollection.findOne(query);
res.send(result);
});
//get api with filter email
app.get("/myitem", verifyJWT, async (req, res) => {
const decodeEmail = req.decoded.email;
const email = req.query.email;
if (email === decodeEmail) {
const query = { email: email };
const cursor = fruitCollection.find(query);
const result = await cursor.toArray();
res.send(result);
} else {
res.status(403).send({ message: "Forbidden Access" });
}
});
//delete api
app.delete("/myitem/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: ObjectId(id) };
const result = await fruitCollection.deleteOne(query);
res.send(result);
});
//post data
app.post("/inventory", async (req, res) => {
const newItem = req.body;
const result = await fruitCollection.insertOne(newItem);
res.send(result);
});
//update data for quantity
app.put("/inventory/:id", async (req, res) => {
const id = req.params.id;
const updateQuantity = req.body;
const filter = { _id: ObjectId(id) };
const options = { upsert: true };
const updateDoc = {
$set: {
quantity: updateQuantity.quantity,
},
};
const result = await fruitCollection.updateOne(
filter,
updateDoc,
options
);
res.send(result);
});
//delete item
app.delete("/inventory/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: ObjectId(id) };
const result = await fruitCollection.deleteOne(query);
res.send(result);
});
} finally {
}
}
run().catch(console.dir);
app.get("/", (req, res) => {
res.send("fruits server is running");
});
app.listen(port, () => {
console.log("server is connected on port", port);
});

You must set the header of the Axios first because CORS means that you don't have access to origin resource API, so you need to setup the header of Axios first, you can follow this resource CORS
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})

Related

Cannot read properties node.js

I've got a problem, I wrote a code which should update my user in a db but when I try to do it in Postman I get an information that the programme can't read my property token. Could somebody help me?
My verifytoken.js code
const { response } = require('express');
const jwt = require('jsonwebtoken');
const verifyToken = (req, res, next) => {
const authHeader = res.headers.token;
if(authHeader){
const token = authHeader.split(' ')[1];
jwt.verify(token, process.env.JWT_SEC, (err, user) => {
if(err) res.status(403).json("Token isn't valid");
req.user = user;
next();
})
}else{
return res.status(401).json("You are not authenticated");
}
}
const verifytokenandauth = (req, res, next) => {
verifyToken(req, res, ()=>{
if(req.user.id=== req.params.id || req.user.admin) {
next();
}else{
res.status(403).json("You are not allowed to do this");
}
})
}
module.exports = {verifyToken, verifytokenandauth}
My user.js code
const { verifytokenandauth } = require('./verifytoken');
const {User} = require('../models/user');
const router = require('express').Router();
router.put('/:id', verifytokenandauth, async (req, res) => {
if(req.body.password){
req.body.password = CryptoJs.AES.encrypt(req.body.password, process.env.PASS_SEC).toString()
}
try{
const updateduser = await User.findByIdAndUpdate(req.User.id, {
$set: req.body
},{new: true});
res.status(200).json(updateduser);
}catch(err) {res.status(500).json(err);}
});
module.exports = router
And screenshot from Postman
Thanks in advance :)

login authorization problem, does not pass the token

I am trying to make a login system with authorization, unfortunately the token is not transferred.
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const urlencodedParser = bodyParser.urlencoded({ extended: false });
const mysql = require('mysql');
const validator = require('validator');
const jwt = require('jsonwebtoken');
require('dotenv').config().ACCESS_TOKEN;
const ACCESS_TOKEN = process.env.ACCESS_TOKEN;
const app = express();
app.use(express.json());
const publicDirectoryPath = path.join(__dirname, '../public');
console.log(publicDirectoryPath);
app.use(express.static(publicDirectoryPath));
function generateAccessToken(username) {
return jwt.sign(username, ACCESS_TOKEN, { expiresIn: '1800s' });
}
app.post('/login', urlencodedParser, (req, res) => {
res.get(req.body.username + req.body.password);
const token = generateAccessToken({ username: req.body.username });
res.json(token);
});
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization']
const token = authHeader && authHeader.split(' ')[1]
console.log(token)
if (token == null) return res.sendStatus(401)
jwt.verify(token, ACCESS_TOKEN, (err, user) => {
console.log(err)
if (err) return res.sendStatus(403)
req.user = user
next()
})
}
app.get('/admin', authenticateToken, (req, res) => {
res.send("admin panel");
})
const port = 3000;
app.listen(port, () => {
console.log(`Server run: http://localhost:${port}`);
})
wants him to be redirected to the admin panel after clicking the login button. However, I am stuck at this stage and do not know what to do next:
enter image description here
You should pass the token to the next route
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const urlencodedParser = bodyParser.urlencoded({ extended: false });
const mysql = require('mysql');
const validator = require('validator');
const jwt = require('jsonwebtoken');
require('dotenv').config().ACCESS_TOKEN;
const ACCESS_TOKEN = process.env.ACCESS_TOKEN;
const app = express();
app.use(express.json());
const publicDirectoryPath = path.join(__dirname, '../public');
console.log(publicDirectoryPath);
app.use(express.static(publicDirectoryPath));
function generateAccessToken(username) {
return jwt.sign(username, 'ACCESS_TOKEN', { expiresIn: '1800s' });
}
app.post('/login', urlencodedParser, (req, res) => {
res.get(req.body.username + req.body.password);
const token = generateAccessToken({ username: req.body.username });
res.redirect(`/admin?token=${token}`);
});
function authenticateToken(req, res, next) {
token = req.query.token;
if (token == null) return res.sendStatus(401);
jwt.verify(token, 'ACCESS_TOKEN', (err, user) => {
console.log(err);
if (err) return res.sendStatus(403);
req.user = user;
next();
});
}
app.get('/admin', authenticateToken, (req, res) => {
res.send('admin panel');
});
const port = 3000;
app.listen(port, () => {
console.log(`Server run: http://localhost:${port}`);
});

how to actually use the data requested using discord oauth2

I am not exactly sure how to go about using/accessing the data requested from a discord oauth2 authentication. I have requested to access the guilds the user is in and the username and avatar of the user. I get a successful authentication, but my question is how do i use and access that data? This is my code currently:
server.js
const express = require('express');
const path = require('path');
const app = express();
app.use('/static', express.static(path.join(__dirname, 'static')));
app.get('/', (req, res) => {
res.status(200).sendFile(path.join(__dirname, 'index.html'));
});
app.listen(50451, () => {
console.info('Running on port 50451');
});
app.use('/api/discord', require('./api/discord'));
app.use((err, req, res, next) => {
switch (err.message) {
case 'NoCodeProvided':
return res.status(400).send({
status: 'ERROR',
error: err.message,
});
default:
return res.status(500).send({
status: 'ERROR',
error: err.message,
});
}
});
discord.js
const express = require('express');
const dotenv = require('dotenv').config()
const fetch = require('node-fetch');
const btoa = require('btoa');
const { catchAsync } = require('../utils');
const router = express.Router();
const scopes = ['identify', 'guilds'];
const CLIENT_ID = process.env.CLIENT_ID;
const CLIENT_SECRET = process.env.CLIENT_SECRET;
const redirect =
encodeURIComponent('http://localhost:50451/api/discord/callback');
router.get('/login', (req, res) => {
res.redirect(`https://discordapp.com/api/oauth2/authorize?client_id=${CLIENT_ID}&redirect_uri=${redirect}&response_type=code&scope=identify%20guilds`);
});
router.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();
res.redirect(`/success/?token=${json.access_token}`);
}));
module.exports = router;
Any help will be greatly appreciated. Thanks!
It's almost the same as the way you use the req.query.code to get the access_token.
const fetchDiscordUserInfo = await fetch('http://discordapp.com/api/users/#me', {
headers: {
Authorization: `Bearer ${json.access_token}`,
}
});
const userInfo = await fetchDiscordUserInfo.json();
yourUserId = `${userInfo.id}`;
yourUserName = `${userInfo.username}`;
// or simply...
console.log(userInfo);

Access req.user to save id to mongoDB

I'm currently having an issue with figuring out how I can access req.user so I can get the logged in users id and save it with the items that they save on the web page. That way when they load the web page they only get their items. The only place I know where I have access to req.user is in my /router/auth.js file. I want to figure out a way to access it in a different router file.
router/auth.js
const express = require('express');
const passport = require('passport');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const config = require('../config');
const router = express.Router();
const createAuthToken = function (user) {
return jwt.sign({ user }, config.JWT_SECRET, {
subject: user.username,
expiresIn: config.JWT_EXPIRY,
algorithm: 'HS256'
});
};
const localAuth = passport.authenticate('local', { session: false });
router.use(bodyParser.json());
router.post('/login', localAuth, (req, res) => {
const authToken = createAuthToken(req.user.serialize());
res.json({ authToken });
});
const jwtAuth = passport.authenticate('jwt', { session: false });
router.post('/refresh', jwtAuth, (req, res) => {
const authToken = createAuthToken(req.user);
res.json({ authToken });
});
/router/portfolio.js
router.post('/:id', (req, res) => {
const id = req.params.id;
const { holdings } = req.body;
CryptoPortfolio.findOne({ id }, (err, existingCoin) => {
if (existingCoin === null) {
getCoins(id)
.then(x => x[0])
.then(value =>
CryptoPortfolio.create({
id: value.id,
holdings,
_creator: this is where I want to add req.user.id
}).then(() => value))
.then(newItem => {
res.status(201).json(newItem);
})
.catch(err => {
console.error(err);
res.status(500).json({ message: 'Internal server error' });
});
} else {
const capitalizedId = id.charAt(0).toUpperCase() + id.slice(1);
res.json(`${capitalizedId} already in watchlist`);
}
});
});
You can define global variable and use it using middleware.
app.js
// Global Vars
app.use(function (req, res, next) {
res.locals.user = req.user
next();
});
route.js
router.get('/', function(req, res) {
CryptoPortfolio.find({}, function(err, crypto) {
console.log('CryptoPortfolio : ',crypto);
res.render('view/crypto', {
user : res.locals.user // <= here
});
});
});
I hope it would be helpful :)
I figured out that I wasn't using the code below on any of the necessary routes. Implemented it and I can now access req.user.
const jwtAuth = passport.authenticate('jwt', { session: false });

Cannot PUT error in Node Express app

My get and post APIs are working, but for some reason my app.put isn't.
When I hit localhost:3001/contacts/1 as a PUT in PostMan, I don't even see my simple console.log:
app.put('/api/contacts:id', (req, res) => {
console.log('req.params.id', req.params.id);
res.json(contact);
});
app.put
app.put('/api/contacts:id', (req, res) => {
console.log('req.params.id', req.params.id);
res.json(contact);
});
Full server.js code
// Requires ////////////////////////////////////////////////////////////////////
const express = require('express');
const app = express();
const bodyParser = require('body-parser'); // req.body
const cors = require('cors');
const R = require('ramda');
// Variables ///////////////////////////////////////////////////////////////////
const hostname = 'localhost';
const port = 3001;
let contacts = require('./data');
// Logic ///////////////////////////////////////////////////////////////////////
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
app.get('/api/contacts', (req, res) => {
if (!contacts || R.isEmpty(contacts)) returnError(res, 'No Contacts found');
res.json(contacts);
});
app.get('/api/contacts/:id', (req, res) => {
const contact = contacts.filter(contact => contact.id == req.params.id);
if (R.isEmpty(contact)) returnError(res, 'No Contact found');
res.json(R.head(contact));
});
app.post('/api/contacts', (req, res) => {
const contact = {
id: contacts.length + 1,
first_name: req.body.first_name,
last_name: req.body.last_name,
email: req.body.email,
website: req.body.website
}
contacts.push(contact);
res.json(contact);
});
app.put('/api/contacts:id', (req, res) => {
console.log('req.params.id', req.params.id);
// const contact = contacts.filter(contact => {
// return contact.id == req.params.id
// })[0];
// console.log('1 contact', contact);
// const index = contacts.indexOf(contact);
// const keys = Object.keys(req.body);
// keys.forEach(key => {
// contact[key] = req.body[key];
// });
// console.log('2 contact', contact);
// contacts[index] = contact;
// console.log('contacts', contacts);
// res.json(contacts[index]);
res.json(contact);
});
const returnError = (res, msg) => res.status(404).json({ message: msg });
app.listen(port, hostname, () => {
console.log(`server is running at http://${hostname}:${port}`);
});
Looks like a typo in this line:
app.put('/api/contacts:id', (req, res) => {
Add a '/' to read:
app.put('/api/contacts/:id', (req, res) => {
Your URL looks like this:
app.put('/api/contacts:id', (req, res) => {,
But it should be like this:
app.put('/api/contacts/:id', (req, res) => {

Categories

Resources