Preview a JasperReports Server 8.0.0 report with Axios - axios

I am trying to preview a JasperReports Server report through Axios, the problem is that when I run it (localhost:port) it keeps loading and does nothing, any help on this?
const express = require('express')
const axios = require("axios")
const app = express()
app.get('/', async function(req,res){
try {
const url = "http://localhost:8080/jasperserver/rest_v2/reports/Re013.pdf"
const params = {
AMB_OCULTO : "123",
AMB : "123",
INS : "FF",
ORD_INI: "419435",
ORD_FIN: "419435"
}
const file = await axios.get(url, {
params: params,
responseType: "stream",
auth:{
username: "jasperadmin",
password: "jasperadmin"
}
})
res.writeHead(200,{"Content-Type":"application/pdf"})
file.data.pipe(res)
} catch (error) {
console.log(error)
}
})
app.listen(4000,()=>{
console.log('')
})

Related

unstable_getServerSession to secure apis (nextAuth)

i need to secure the API so that only authorized user can access them. I followed the documentation in this link https://next-auth.js.org/tutorials/securing-pages-and-api-routes#securing-api-routes but apparently I am not retrieving the session.
I am able to console.log the authOptions but if I try to console log the session (and I am logged in), it logs "null"
This is the code
pages/api/profile.js
import prisma from "../../../lib/prisma";
import { unstable_getServerSession } from "next-auth/next";
import { authOptions } from "../auth/[...nextauth]";
export default async function handler(req, res) {
const session = await unstable_getServerSession(req, res, authOptions);
console.log("SESSION", session); // this logs "null"
if (!session) {
return res.status(401).json("Not authorized");
}
try {
const user = await prisma.user.findUnique({
where: { email: session.user.email },
});
return res.status(200).json(user);
} catch (error) {
console.error(error);
return res
.status(503)
.json(
"Our server is not able to process the request at the moment, please try again later!"
);
}
pages/api/auth/[...nextauth].js
import NextAuth from "next-auth";
import CognitoProvider from "next-auth/providers/cognito";
import prisma from "../../../lib/prisma";
export const authOptions = {
providers: [
CognitoProvider({
clientId: process.env.CLIENTID_NEXTAUTH,
issuer: process.env.COGNITO_ISSUER,
clientSecret: process.env.CLIENTSECRET_NEXTAUTH,
}),
],
session: {
strategy: "jwt",
maxAge: 30 * 24 * 60 * 60,
updateAge: 24 * 60 * 60,
},
callbacks: {
async jwt({ token, account }) {
if (account) {
token.accessToken = account.access_token;
}
return token;
},
async session({ session, token }) {
const user = await prisma.user.findUnique({
where: { email: session?.user?.email },
});
if (!user) throw new Error("User not found in the database.");
const mySession = {
...session,
accessToken: token.accessToken,
email: user.email,
};
return mySession;
},
},
};
export default NextAuth(authOptions);
pages/dashboard/index.js
import axios from "axios";
import React, { useState } from "react";
import { getSession, useSession } from "next-auth/react";
const Dashboard = (props) => {
let { data: session, status } = useSession();
if (status === "loading") {
return <p>Loading...</p>;
}
if (status === "unauthenticated") {
window.location.reload();
}
return (
<p>
{props.userInfo.name}
</p>
);
};
export default Dashboard;
export async function getServerSideProps(context) {
const session = await getSession(context);
if (!session) {
return {
redirect: {
destination: "/",
permanent: false,
},
};
}
console.log("SESSION IN INDEX", session); // this logs the session
const userInfo = await axios.get(
`${process.env.BASE_URL}/api/profile?email=${session.email}`
);
return {
props: {
session,
userInfo: userInfo.data ? userInfo.data : null,
},
};
}
so when I login, I can see the SESSION in INDEX but when I hit the api/profile, the session from unstable_getServerSession is null, so I canno see nothing in the dashboard
resolved:
when calling the api you need to pass the headers, for example in the dashboard/index.js
const userInfo = await axios.get(
`${process.env.BASE_URL}/api/profiles/profile?email=${session.email}`,
{
withCredentials: true,
headers: {
Cookie: context.req.headers.cookie,
},
}
);
while in the API endpoint
import { getServerSession, getSession } from "next-auth/next";
import { authOptions } from "../auth/[...nextauth]";
export default async function handler(req, res) {
const session = await getServerSession(req, res, authOptions);
console.log("SESSION", session);
//your code
}

mongodb atlas database not accepting POST request

I'm currently trying to teach myself REST APIs through following a tutorial and encountering a problem where after trying to send a POST request through Postman, it reaches an error statement. The API accepts the POST json data as it appears in the terminal using console.log(req.body) so I believe its likely a problem with the mongodb connection.
posts.js file:
const express = require('express');
const router = express.Router();
const Post = require('../models/Post');
router.get('/', (req, res) => {
res.send('It works!');
});
router.get('/', async (req, res) => {
try {
const posts = await Post.find();
res.json(posts);
} catch(err){
console.log("Error 2")
res.status(404).json({message:err});
}
});
router.post('/', async (req, res) => {
const post = new Post({
title: req.body.title,
description: req.body.description
});
try {
const savedPost = await post.save()
res.json(savedPost);
} catch (err) {
console.log(req.body)
console.log("Error encountered when attempting to POST")
res.status(404).json({ message: err });
}
});
module.exports = router;
app.js:
const express = require('express');;
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
require('dotenv/config');
const app = express();
app.use(bodyParser.json());
app.use(express.json());
//import the routes
const postsRoute = require('./routes/posts');
//middleware
app.use('/posts', postsRoute);
//Routes
app.get('/', (req,res) => {
res.send('Welcome to the Home Page');
});
//Connect to DB
mongoose.connect(
process.env.DB_CONNECTION,
{useNewUrlParser:true} ,
() => {console.log('Succesfully connected to DB')
});
//Start server listening
console.log('App is running on: http://localhost:3000');
app.listen(3000);
package.json:
{
"name": "api",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon app.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.2",
"dotenv": "^16.0.0",
"express": "^4.17.3",
"mongoose": "^6.2.9",
"nodemon": "^2.0.15"
}
}
Schema file
const mongoose = require('mongoose');
const PostSchema = mongoose.Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('Posts', PostSchema);
console log:
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
App is running on: http://localhost:3000
Succesfully connected to DB
{ title: 'test', description: 'test2' }
Error encountered when attempting to POST

Problem to send data on Express.js / MongoDB

i get error about Body-Parser when i post data with Postman on localhost:3000/send-data
, i thought it can get fixed with express.json() but it didn't, also what is the simplest way to post data to mongoDB with React-native?
here are my codes:
app.js :
const express = require('express')
const app = express();
const mongoose = require('mongoose')
const bodyParser = require('body-parser')
require("./ads")
app.use(express.json());
app.use(express.urlencoded({
extended: true
}));
const Ads = mongoose.model("ads")
const mongoURI = *
mongoose.connect(mongoURI, {
useNewUrlParser : true,
useUnifiedTopology: true
})
mongoose.connection.on("connected",() => {
console.log("connected to server")
})
mongoose.connection.on("error",(err) => {
console.log("error",error)
})
app.post('/send-data',(req,res) => {
const ads = new Ads({
name : req.body.name,
title : req.body.title,
title2 : req.body.title2,
})
ads.save()
.then(data => {
console.log(data)
res.send("seccsudss")
}).catch(err => {
console.log(err)
})
})
app.get('/',(req,res) => {
res.send("welcome to nodejs")
})
app.listen(3000,() => {
console.log('listening on 3000')
})
and error i get is :
SyntaxError: Unexpected token } in JSON at position 185
at JSON.parse (<anonymous>)
at parse (/home/kian/project/project/project/node_modules/body-parser/lib/types/json.js:89:19)
at /home/kian/project/project/project/node_modules/body-parser/lib/read.js:121:18
at invokeCallback (/home/kian/project/project/project/node_modules/raw-body/index.js:224:16)
at done (/home/kian/project/project/project/node_modules/raw-body/index.js:213:7)
at IncomingMessage.onEnd (/home/kian/project/project/project/node_modules/raw-body/index.js:273:7)
at IncomingMessage.emit (events.js:314:20)
at endReadableNT (_stream_readable.js:1241:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
You can pass string as json keys
{
"name" : req.body.name,
"title" : req.body.title,
"title2" : req.body.title2
}

cant get current user with axios get

In my API is the current user (I have logged in with passport) but when I make an Axios get request the data field is empty. I absolutely don't know what to do :(
<script>
import axios from "axios"
export default {
name: 'Home',
components: {
},
data: function() {
return {
user: axios.get('http://127.0.0.1:3000/api/').then(response => this.user = response)
}
},
methods: {
}
}
</script>
Here is the output:
Here is my API:
Edit: Here is my Backend File:
const express = require('express');
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
const cors = require('cors')
const passport = require('passport')
let LocalStrategy = require('passport-local').Strategy;
const session = require('express-session')
var app = express();
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
const port = 3000
app.use(cors({
methods:['GET','POST'],
credentials: true
}))
app.use(express.static('public'))
//Passport setup
app.use(session({
secret: 'test',
resave: false,
saveUninitialized: false,
secure: true
}))
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
const apiRoutes = require('./apiRoutes')
app.use(cors())
app.use('/api', apiRoutes)
// connect to database
mongoose.connect('mongodb+srv://#cluster0.dhsiv.mongodb.net/test?retryWrites=true&w=majority',
{useNewUrlParser: true, useUnifiedTopology: true}, () => {
console.log('Erfolgreich connected')
})
app.listen(port, () => {
console.log('server is running on port '+port)
})
module.exports;
I hope someone can help me. Thanks a lot guys :)
i have also change my data and run the axios get in mounted but it doesnt change anything.
Routes:
const { _ } = require('core-js');
const { Mongoose } = require('mongoose');
const { find, where } = require('./models/userModel');
const userModel = require('./models/userModel');
let router = require('express').Router();
const bcrypt = require('bcryptjs')
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
let jwt = require('jsonwebtoken');
const { static } = require('express');
require('./passportConfig')
router.get("/", (req, res) => {
res.json({
user: req.user
});
});

Cannot get a response from PostgreSQL server

I freely admit that I am completely new to next-auth and the documentation for Credentials is understandably very light. I have got the email link process to work perfectly and will be moving users across top this.
Unfortunately, I have a lot of user data that will require credentials to login and, after spending a few days getting nowhere, I just want to get some idea of what I am doing wrong! This is my [...nextauth].js file:
import NextAuth from "next-auth";
import Providers from "next-auth/providers";
import axios from 'axios'
const options = {
providers: [
Providers.Email({
server: {
host: process.env.EMAIL_SERVER_HOST,
port: process.env.EMAIL_SERVER_PORT,
auth: {
user: process.env.EMAIL_SERVER_USER,
pass: process.env.EMAIL_SERVER_PASSWORD
}
},
from: process.env.EMAIL_FROM
}),
Providers.Credentials({
credentials: {
mem_num: { label: "Membership Number", type: "text", placeholder: "12345" },
password: { label: "Password", type: "text" }
},
authorize: async (credentials) => {
console.log("credentials: ", credentials)
try {
const data = {
mem_num: credentials.mem_num,
password: credentials.password
}
const user = await login(data)
if (user) {
console.log('user:', user)
return user
}
} catch (error) {
if (error.response) {
console.log(error.response)
Promise.reject(new Error('Invalid Number and Password combination'))
}
}
}
})
],
site: process.env.NEXTAUTH_URL || "http://localhost:3000",
database: process.env.DATABASE_URL,
session: {
// Use JSON Web Tokens for session instead of database sessions.
// This option can be used with or without a database for users/accounts.
// Note: `jwt` is automatically set to `true` if no database is specified.
jwt: true,
},
}
const login = async data => {
var config = {
headers: {
'Content-Type': "application/json; charset=utf-8",
'corsOrigin': '*',
"Access-Control-Allow-Origin": "*"
}
};
const url = process.env.DATABASE_URL;
const result = await axios.post(url, data, config);
console.log('result', result);
return result;
};
export default (req, res) => NextAuth(req, res, options);