Related
How can punt the value of heorku query price_housing in to xValues in my chart?
In my html I have this chartjs that I want show in website
<canvas id="myChart" ></canvas>
<script>
var xValues = [50,60,70,80,90,100,110,120,130,140,150];
var yValues = [7,8,8,9,9,9,10,11,14,14,15];
new Chart("myChart", {
type: "line",
data: {
labels: xValues,
datasets: [{
fill: false,
lineTension: 0,
backgroundColor: "rgba(0,0,255,1.0)",
borderColor: "rgba(0,0,255,0.1)",
data: yValues
}]
},
options: {
legend: {display: true},
scales: {
yAxes: [{ticks: {min: 6, max:16}}],
}
}
});
</script>
And I have this connection with javascript that connect to Heroku and make query to extract price housing.
const {Client} = require('pg');
// Heroku connection
const connectionString =''
// Config connection
const connectionData = {
connectionString : connectionString,
ssl:{rejectUnauthorized: false}
};
const client = new Client(connectionData);
client.connect();
// Querys
const price_housing = client.query('SELECT price_housing FROM year_prince_housing ')
.then(response => {
console.log(response.rows)
client.end()
})
.catch(err => {
client.end()
});
I am trying to create a simple API call to create a Google Calendar Event with a Google Meet link in it but it seems I am unable to do so.
I looked up the Calendar API Documentation and have seen various examples but it still doesn't work for me. I am using a Service Account on NodeJS and a React frontend. Here below is the source code of my project.
const { google } = require('googleapis');
const { GoogleAuth } = require('google-auth-library');
var express = require('express');
var router = express.Router();
const SCOPES = ['https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/calendar.addons.execute', 'https://www.googleapis.com/auth/calendar.settings.readonly', 'https://www.googleapis.com/auth/calendar.events'];
const GOOGLE_PRIVATE_KEY = "MY_PRIVATE_KEY"
const GOOGLE_CLIENT_EMAIL = "MY_SERVICE_ACCOUNT"
const GOOGLE_PROJECT_NUMBER = "MY_PROJECT_NUMBER"
const GOOGLE_CALENDAR_ID = "MY_CALENDAR_ID"
const jwtClient = new google.auth.JWT(
GOOGLE_CLIENT_EMAIL,
null,
GOOGLE_PRIVATE_KEY,
SCOPES,
"MY_PERSONAL_EMAIL"
);
const calendar = google.calendar({
version: 'v3',
project: GOOGLE_PROJECT_NUMBER,
auth: jwtClient
});
const auth = new GoogleAuth({
keyFile: 'credentials.json',
scopes: 'https://www.googleapis.com/auth/calendar', //full access to edit calendar
});
auth.getClient();
router.get("/demo", (req, res) => {
var event = {
'summary': 'My first event!',
'location': 'Hyderabad,India',
'description': 'First event with nodeJS!',
'start': {
'dateTime': '2022-06-28T09:00:00-07:00',
'timeZone': 'Asia/Dhaka',
},
'end': {
'dateTime': '2022-06-29T17:00:00-07:00',
'timeZone': 'Asia/Dhaka',
},
'attendees': [],
'reminders': {
'useDefault': false,
'overrides': [
{ 'method': 'email', 'minutes': 24 * 60 },
{ 'method': 'popup', 'minutes': 10 },
],
},
"conferenceData": {
'createRequest': {
"requestId": getRandomString(),
"conferenceSolution": {
"key": {
"type": "hangoutsMeet",
}
},
}
}
};
calendar.events.insert({
auth: auth,
calendarId: GOOGLE_CALENDAR_ID,
requestBody: event,
conferenceDataVersion: 1,
}, function (err, event) {
if (err) {
console.log('There was an error contacting the Calendar service: ' + err);
return;
}
console.log('Event created: %s', event.data);
res.jsonp("Event successfully created!");
});
})
Did you solve the Issue?
I also looked into this part because of a side project, and I'll share the code I've had success with.
I'm not sure which part is different when I look at it.
I hope this code helps.
/* index.js */
const fs = require('fs').promises;
const path = require('path');
const process = require('process');
const {authenticate} = require('#google-cloud/local-auth');
const {google} = require('googleapis');
const { v4: uuidv4 } = require('uuid');
const express = require('express');
const app = express()
// OAuth scope
const SCOPES = ['https://www.googleapis.com/auth/calendar.events'];
const TOKEN_PATH = path.join(process.cwd(), 'token.json');
const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json');
/* Reads previously authorized credentials from the save file. */
async function loadSavedCredentialsIfExist() {
try {
const content = await fs.readFile(TOKEN_PATH);
const credentials = JSON.parse(content);
return google.auth.fromJSON(credentials);
} catch (err) {
return null;
}
}
/* Serializes credentials to a file compatible with GoogleAUth.fromJSON. */
async function saveCredentials(client) {
const content = await fs.readFile(CREDENTIALS_PATH);
const keys = JSON.parse(content);
const key = keys.installed || keys.web;
const payload = JSON.stringify({
type: 'authorized_user',
client_id: key.client_id,
client_secret: key.client_secret,
refresh_token: client.credentials.refresh_token,
});
await fs.writeFile(TOKEN_PATH, payload);
}
/* Load or request or authorization to call APIs. */
async function authorize() {
let client = await loadSavedCredentialsIfExist();
if (client) {
return client;
}
client = await authenticate({
scopes: SCOPES,
keyfilePath: CREDENTIALS_PATH,
});
if (client.credentials) {
await saveCredentials(client);
}
return client;
}
/**
* #param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
async function inserEvent(auth) {
const calendar = google.calendar({version: 'v3', auth});
const event = {
summary: 'Demo',
description: 'Demo for Google Meet',
start: {
dateTime: '2022-11-20T09:00:00+09:00',
timeZone: 'Asia/Seoul',
},
end: {
dateTime: '2022-11-20T09:30:00+09:00',
timeZone: 'Asia/Seoul',
},
conferenceData: {
createRequest: {
conferenceSolutionKey: {type: 'hangoutsMeet'},
requestId: uuidv4(),
},
},
attendees: [
{email: '${email1}'}, /* insert email */
{email: '${email2}'}, /* insert email */
],
reminders: {
useDefault: false,
overrides: [
{method: 'email', minutes: 60},
{method: 'popup', minutes: 10},
],
},
};
calendar.events.insert({
auth: auth,
calendarId: 'primary',
resource: event,
conferenceDataVersion: 1,
}, function(err, event) {
if (err) {
console.log('There was an error contacting the Calendar service: ' + err);
return;
}
console.log('Event created, google meet link : %s', event.data.hangoutLink);
});
}
app.get("/demo", (rqe, res) => {
authorize().then(inserEvent).catch(console.error);
res.send('Good');
})
app.listen(3000, () => {
console.log('listening on port 3000');
})
**I am getting the error when I am connecting the frontend code as well as backend code with the database maybe the problem might be in front end but pls let me know the meaning of the error because I am newbie.I am getting the error on register pls help me and also when I register the website using frontend it shows me error on **localhost/register
enter image description here
const express = require('express');
const { listen } = require('express/lib/application');
const bodyParser=require('body-parser');
const bcrypt=require('bcrypt-nodejs')
const cors = require('cors')
const knex = require('knex');
const { response } = require('express');
const db=knex({
client: 'pg',
connection: {
host : '127.0.0.1',
user : 'postgres',
password : '224898',
database : 'smart-brain'
}
});
const app = express();
app.use(bodyParser.json());
app.use(cors())
const database={
users:[
{
id:'123',
name:'John',
email:'John#gmail.com',
password:'ABC',
entries:0,
joined:new Date()
},
{
id:'124',
name:'ABC',
email:'ABC',
password:'123',
entries:0,
joined:new Date()
}
],
login:[
{
id:'987',
hash:'',
email:'John#gmail.com'
}
]
}
app.get('/' ,(req,res)=>{
res.send(database.users);
})
app.post('/signin',(req,res)=>{
if(req.body.email===database.users[0].email && req.body.password===database.users[0].password){
res.json(database.users[0]);
}else{
res.status(400).json('error login in');
}
})
app.post('/register',(req,res)=>{
const{email,name,password}=req.body;
db('users')
.returning('*')
.insert({
email:email,
name:name,
joined: new Date()
})
.then(user=>{
res.json(user[0]);
})
. catch(err => console.log(err))
})
app.get('/profile/:id',(req,res)=>{
const{id}=req.params;
let found=false;
database.users.forEach(user=>{
if(user.id===id){
found=true;
return res.json(user);
}
})
if(!found){
res.status(400).json('not found');
}
})
app.put('/image',(req,res)=>{
const{id}=req.body;
let found=false;
database.users.forEach(user=>{
if(user.id===id){
found=true;
user.entries++
return res.json(user.entries);
}
})
if(!found){
res.status(400).json('not found');
}
})
// // Load hash from your password DB.
// bcrypt.compare("bacon", hash, function(err, res) {
// // res == true
// });
// bcrypt.compare("veggies", hash, function(err, res) {
// // res = false
// });
app.listen(3000,()=>{
console.log('app is running on port 3000 ');
})
AND ALSO I AM SHARING FRONTEND APP.JS CODE
APP.js code
import './App.css';
import Navigation from './Components/Navigation/Navigation';
import FaceRecognition from './Components/FaceRecognition/FaceRecognition';
import Logo from './Components/Logo/Logo'
import ImageLinkForm from './Components/ImageLinkForm/ImageLinkForm'
import Rank from './Components/Rank/Rank'
import { Component } from 'react';
import Particles from "react-tsparticles";
import { loadFull } from "tsparticles";
import SignIn from './Components/SignIn/SignIn';
import Register from './Components/Register/Register'
const USER_ID = 'aad';
const PAT = 'bd69e06e68f244ed83b9ce09ee560e7c';
const APP_ID = 'aaa';
const MODEL_ID = 'face-detection';
const MODEL_VERSION_ID = '45fb9a671625463fa646c3523a3087d5';
const particlesOption = {
fpsLimit: 120,
particles: {
links: {
color: "#ffffff",
distance: 150,
enable: true,
opacity: 0.5,
width: 1,
},
collisions: {
enable: true,
},
move: {
direction: "none",
enable: true,
outModes: {
default: "bounce",
},
random: true,
speed: 5,
straight: true,
},
},
detectRetina: true,
}
const particlesInit = async (main) => {
await loadFull(main);
};
const initialState = {
input: '',
imageUrl: '',
box: {},
route:'signin',
isSignedIn:false,
user: {
id: '',
name: '',
email: '',
joined: '',
entries: 0
}
};
class App extends Component {
constructor() {
super();
this.state = initialState;
};
loadUser = (data) => {
this.setState({
user: {
id: data.id,
name: data.name,
email: data.email,
entries: data.entries,
joined: data.joined
}
})
}
apiData = () => {
const raw = JSON.stringify({
"user_app_id": {
"user_id": USER_ID,
"app_id": APP_ID
},
"inputs": [
{
"data": {
"image": {
"url": this.state.input
}
}
}
]
});
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Authorization': 'Key ' + PAT
},
body: raw
};
return requestOptions;
}
displayFaceBox = (box) => {
this.setState({ box: box });
}
onInputChange=(event) =>{
this.setState({input: event.target.value});
}
onImageSubmit = () => {
this.setState({ imageUrl: this.state.input });
const requestOptions = this.apiData();
fetch("https://api.clarifai.com/v2/models/" + MODEL_ID + "/versions/" + MODEL_VERSION_ID + "/outputs", requestOptions)
.then(response => response.text())
.then(result => JSON.parse(result))
.then(obj => {
if (obj) {
fetch('http://localhost:3000/image', {
method: 'put',
headers: {'content-type': 'application/json'},
body: JSON.stringify({
id: this.state.user.id
})
})
.then(response => response.json())
.then(count => {
this.setState(Object.assign(this.state.user, {entries: count}))
})
}
this.displayFaceBox(this.calculateFaceLocation(obj))
})
.catch(error => console.log('error', error));
}
calculateFaceLocation = (data) => {
const clarifaiFace = data.outputs[0].data.regions[0].region_info.bounding_box;
const image = document.getElementById('inputimage');
const width = Number(image.width);
const height = Number(image.height);
return ({
leftCol: clarifaiFace.left_col * width,
topRow: clarifaiFace.top_row * height,
rightCol: width - (clarifaiFace.right_col * width),
bottomRow: height - (clarifaiFace.bottom_row * height),
})
}
onRouteChange=(route)=>{
if(route==='signout'){
this.setState({isSignedIn:false})
}else if(route==='home'){
this.setState({isSignedIn:true})
}
this.setState({route:route})
}
render(){
const { imageUrl, box ,isSignedIn,route} = this.state;
return (
<div className="App">
<Particles className='particles'
init={particlesInit}
options={particlesOption}
/>
<Navigation isSignedIn={isSignedIn} onRouteChange={this.onRouteChange} />{ route==='home'?
<div>
<Logo />
<Rank name={this.state.user.name} entries={this.state.user.entries}/>
<ImageLinkForm onInputChange={this.onInputChange}
onImageSubmit={this.onImageSubmit}/>
<FaceRecognition box={box} imageUrl={imageUrl} />
</div> :(
route==='signin'?
<SignIn loadUser={this.loadUser} onRouteChange={this.onRouteChange} />
: <Register loadUser={this.loadUser}onRouteChange={this.onRouteChange}/>
)
}
</div>
);
}
}
export default App;
Do not use images for textual information, copy and paste the text into the question. This would make the following easier.
From error message code:23502. If you go here Error codes you find that corresponds to 23502 not_null_violation. So the value that is being set to NULL is being entered into a column that has NOT NULL set. Your choices are:
a) Make sure the value is not set to NULL.
b) If you can have NULL values in the column drop the NOT NULL constraint.
So on the front end I'm using this function to have the user Log In if they have a This Function only works at the time of log in and after if the users just navigates to a different page on the site then it resets the userData state's values to undefined, The api link "http://localhost:5000/users/isTokenValid" returns either true or false
const [adminData, setAdminData] = useState({
token: undefined,
user: undefined,
});
const [authData, setAuthData] = useState(undefined);
const [userData, setUserData] = useState({
token: undefined,
user: undefined,
});
useEffect(() => {
const checkLoggedIn = async () => {
let token = localStorage.getItem('auth-token');
if (token === null) {
localStorage.setItem('auth-token', '');
token = '';
}
const tokenRes = await axios.post(
'http://localhost:5000/users/isTokenValid',
null,
{ headers: { 'x-auth-token': token } },
);
if (tokenRes.data) {
const userRes = axios.get('http://localhost:5000/users/', {
headers: { 'x-auth-token': token },
});
setUserData({
token,
user: userRes.data,
});
}
};
checkLoggedIn();
}, []);
return (
<UserContext.Provider value={{ userData, setUserData }}>
<AdminContext.Provider value={{ adminData, setAdminData }}>
<AuthContext.Provider value={{ authData, setAuthData }}>
<Routes />
</AuthContext.Provider>
</AdminContext.Provider>
</UserContext.Provider>
);
I didn't add await.
if (tokenRes.data) {
const userRes = await axios.get('http://localhost:5000/users/', {
headers: { 'x-auth-token': token },
});
setUserData({
token,
user: userRes.data,
});
}
I have a nodejs code where I can download a pdf file since browser when I send 2 arguments in post request: fname and lname.
I am using express and pdfmake package in the backend.
const express = require('express');
const router = express.Router();
const pdfMake = require('../pdfmake/pdfmake');
const vfsFonts = require('../pdfmake/vfs_fonts');
pdfMake.vfs = vfsFonts.pdfMake.vfs;
router.post('/pdf', (req, res, next) => {
//res.send('PDF');
const fname = req.body.fname;
const lname = req.body.lname;
var documentDefinition = {
content: [{
image: 'data:image/png;base64 more code',
width: 200,
alignment: 'center'
},
{ text: '\nGrupo de inspecciones predictivas', style: 'header', alignment: 'center' },
{ text: 'Reporte de inspección\n\n', style: 'subheader', alignment: 'center' },
'El siguiente reporte tiene como objetivo describir los resultados encontrados a partir de la inspección en la fecha específica.',
{ text: 'Resumen del reporte', style: 'subheader' },
{
style: 'tableExample',
table: {
widths: ['*', 'auto'],
body: [
['Inspector:', { text: `${ fname }`, noWrap: true }],
['Flota:', { text: '', noWrap: true }],
['Número de flota:', { text: '', noWrap: true }],
['Técnica:', { text: '', noWrap: true }],
['Fecha de inicio:', { text: '', noWrap: true }],
]
}
},
],
styles: {
header: {
fontSize: 18,
bold: true,
margin: [0, 0, 0, 10]
},
subheader: {
fontSize: 16,
bold: true,
margin: [0, 10, 0, 5]
},
tableExample: {
margin: [0, 5, 0, 15]
},
tableHeader: {
bold: true,
fontSize: 13,
color: 'black'
}
},
defaultStyle: {
// alignment: 'justify'
}
};
const pdfDoc = pdfMake.createPdf(documentDefinition);
pdfDoc.getBase64((data) => {
res.writeHead(200, {
'Content-Type': 'application/pdf',
'Content-Disposition': 'attachment;filename="filename.pdf"'
});
const download = Buffer.from(data.toString('utf-8'), 'base64');
res.end(download);
});
});
However, as I mentioned above, this code apparently only return de pdf to browsers.
I need to download the pdf file to the Android/IOS storage in the Flutter app.
A good way to accomplish this would be to create a simple URL endpoint that returns the file directly. In your flutter app, you can use the file downloader to download the file directly to the app using something like this:
final taskId = await FlutterDownloader.enqueue(
url: 'your download link',
savedDir: 'the path of directory where you want to save downloaded files',
showNotification: true, // show download progress in status bar (for Android)
openFileFromNotification: true, // click on notification to open downloaded file (for Android)
);
You can find details on how to set up an endpoint for that here.
I have used google cloud platform to store the pdf generated by nodeJS. You can do it following the next articles: https://mzmuse.com/blog/how-to-upload-to-firebase-storage-in-node
https://github.com/googleapis/google-cloud-node/issues/2334
pdfDoc.getBase64((data) => {
const keyFilename = "./myGoogleKey.json";
const projectId = "my-name-project";
const bucketName = `${projectId}.appspot.com`;
var GoogleCloudStorage = require('#google-cloud/storage');
const gcs = GoogleCloudStorage({
projectId,
keyFilename
});
const bucket = gcs.bucket(bucketName);
const gcsname = 'reporte.pdf';
const file = bucket.file(gcsname);
var buff = Buffer.from(data.toString('utf-8'), 'base64');
const stream = file.createWriteStream({
metadata: {
contentType: 'application/pdf'
}
});
stream.on('error', (err) => {
console.log(err);
});
stream.on('finish', () => {
console.log(gcsname);
});
stream.end(buff);
res.status(200).send('Succesfully.');
});
});
This will generate a URL and you can follow the last answer given by Esh above.