This is my package.json:
{
"name": "aracelli-v-photography-website",
"version": "0.0.3",
"private": true,
"description": "a photography website",
"main": "api/server.js",
"scripts": {
"start": "concurrently -p \"{name}\" -c \"green\" -n \"database,node\" \"npx sequelize-cli db:migrate --env=production\" \"HOSTING_DIR=livebuild/ node server\"",
"dev": "concurrently -p \"{time}-{name}\" -c \"green\" -n \"react,nodemon\" \"react-scripts build\" \"nodemon server\"",
"test": "concurrently -p \"{time}-{name}\" -c \"green\" -n \"database,node\" \"DATABASE_URL=$(heroku config:get DATABASE_URL -a aracelli-v-photography) npx sequelize-cli db:migrate --env=production\" \"DATABASE_URL=$(heroku config:get DATABASE_URL -a aracelli-v-photography) node server\"",
"build": "BASE_URL=\"https://aracelli-v-photography.herokuapp.com/api\" react-scripts build && rm -rf livebuild && mv build livebuild"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Aracelli-V-Photography/aracelli-v-photography-website.git"
},
"author": "jadelynnmasker",
"license": "GPL-3.0-or-later",
"bugs": {
"url": "https://github.com/Aracelli-V-Photography/aracelli-v-photography-website/issues"
},
"homepage": "/",
"devDependencies": {
"axios": "^0.21.1",
"eslint": "^7.28.0",
"nodemon": "^2.0.7",
"prettier": "^2.3.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-redux": "^7.2.4",
"react-router-dom": "^5.2.0",
"react-scripts": "^4.0.3",
"redux": "^4.1.0",
"redux-devtools-extension": "^2.13.9",
"redux-thunk": "^2.3.0",
"uuid": "^8.3.2"
},
"dependencies": {
"bcrypt": "^5.0.1",
"concurrently": "^6.2.0",
"njwt": "^1.1.0",
"pg": "^8.6.0",
"pg-hstore": "^2.3.4",
"sequelize": "^6.6.2",
"sequelize-cli": "^6.2.0"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}My question is, why doesn't the server deploy with react
}
And my server.js:
const http = require("http");
const url = require("url");
const fs = require("fs");
const path = require("path");
const routes = require("./config/routes");
const PORT = process.env.PORT || 3000;
const HOME_DIRECTORY = process.cwd();
const STATIC_DIRECTORY = process.env.HOSTING_DIR || "build/";
const server = http.createServer(function (request, response) {
try {
process.chdir(HOME_DIRECTORY);
} catch (error) {
console.log(error);
}
if (request.url.split("/")[1] !== "api") {
const parsedUrl = url.parse(request.url);
let pathname = `.${parsedUrl.pathname}`;
const extension = path.parse(pathname).ext;
try {
process.chdir(STATIC_DIRECTORY);
} catch (error) {
return console.log(error);
}
const mapExtensionsToContentType = {
".ico": "image/x-icon",
".html": "text/html",
".js": "text/javascript",
".json": "application/json",
".css": "text/css",
".png": "image/png",
".jpg": "image/jpeg",
".wav": "audio/wav",
".mp3": "audio/mpeg",
".svg": "image/svg+xml",
".pdf": "application/pdf",
".doc": "application/msword",
};
fs.exists(pathname, function (exist) {
if (!exist) {
response.statusCode = 301;
response.setHeader("Location", "/");
return response.end(() => {
console.log(
"\nUser probably refreshed the page. Stand by for new session!"
);
});
}
if (pathname === "./") {
pathname += "index.html";
console.log("\nUser joined the site!");
}
fs.readFile(pathname, function (error, data) {
if (error) {
response.statsCode = 500;
response.end(`Error getting the file: ${error}`);
return console.error(`Error getting the file: ${error}`);
}
response.setHeader(
"Content-Type",
mapExtensionsToContentType[extension] || "text/html"
);
response.end(data);
});
});
} else {
const actionPath = `${request.method} ${request.url}`;
const route = routes.find(function (route) {
return actionPath.match(route[0]);
});
if (!route) {
return console.log(`\n${actionPath} -> undefined`);
}
console.log(`\n${actionPath} -> ${route[1]}`);
const [controllerName, method] = route[1].split("#");
const Controller = require(`./controllers/${controllerName}Controller`);
if (request.method !== "POST") {
const controller = new Controller(request, response);
controller[method]();
} else {
let body = "";
request.on("data", function (chunk) {
body += chunk.toString();
});
request.on("end", function () {
controller = new Controller(
request,
response,
JSON.parse(body)
);
controller[method]();
});
}
}
});
server.listen(PORT, function () {
console.log("Server running on port " + PORT);
});
Finally, my /src/redux/common.js, where I think the problem is:
import axiosBase from "axios";
import { v4 as uuidv4, v5 as uuidv5 } from "uuid";
export const axios = axiosBase.create({
baseURL: process.env.BASE_URL || "http://localhost:3000/api",
});
const NAMESPACE = uuidv4();
export function uuid() {
return uuidv5(uuidv4(), NAMESPACE);
}
Basically, I'm trying to host a Node.js server with more knowledge in React than in Node, and I'm stuck here because no matter what I do axios always sends requests to "http://localhost:3000/api". I need to deploy on heroku and have it send requests to heroku instead of my local machine! I looked at the docs for create-react-app and it looks like I am doing it right. I am, however, always using a production build of react because I couldn't figure out where to find the development build. Because of how it's deployed on heroku (my node server serves the react app as well as the api) I don't want my app running on two different ports and needing cors.
With that out of the way, there are basically two solutions to my problem that will make me happy. One is, I could find where the development build is and use the NODE_ENV enviromnent variable to determine whether I am on a server or not. Or, two, I could find a way to make the enviroment variables that I am using work.
Either way, I appreciate your time and consideration. If more information is needed, I will gladly post an update.
There is no problem with your app bro. You have made an error in your package.json. What you have done is include your dependencies in the devDependencies which means that react module is not being installed on your Heroku app.
During the deployment, you will notice that it shows a line pruning devDependencies which means that it's cutting the packages from the list which are in the devDependencies.
Steps to make things right:
You have to include your devDependencies in dependencies
To do so run this command
npm install axios react react-dom react-redux
react-router-dom react-scripts redux redux-devtools-extension redux-thunk uuid --save-prod
Now push your app to Heroku and it will start working.
Related
Receiving an error: this interaction failed, none of my console logs are outputting besides the "logged in as". I have given the bot the correct token as well as permissions for admin, bot, and application.commands
here is my index.js file
const { Client, GatewayIntentBits, Events } = require('discord.js')
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildPresences,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.DirectMessages,
GatewayIntentBits.MessageContent
]
})
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
const options = [
'🐭',
'https://media.giphy.com/media/wJZTbXayokOgbCfyQe/giphy.gif',
'https://media.giphy.com/media/QXh9XnIJetPi0/giphy.gif',
'🐁',
];
client.on(Events.MessageCreate, message => {
console.log(message);
});
client.on(Events.InteractionCreate, interaction => {
console.log(`test1`);
if (!interaction.isCommand()) return;
console.log(`test3`);
if (interaction.commandName === 'hugging-face') {
console.log(`test3`);
interaction.reply(
options[Math.floor(Math.random() * options.length)]
);
}
});
client.login(process.env.TOKEN);
Here is my package.json
{
"name": "discord-slash-bot",
"version": "1.0.0",
"description": "package install",
"main": "index.js",
"scripts": {
"register": "node -r dotenv/config discord-slash-bot/register.js",
"start": "node -r dotenv/config index.js"
},
"keywords": [
"discord.js",
"#discordjs/rest",
"discord-api-types",
"dotenv"
],
"author": "conner",
"license": "ISC",
"dependencies": {
"#discordjs/rest": "^1.5.0",
"axios": "^1.2.3",
"discord-api-types": "^0.37.28",
"discord.js": "^14.7.1",
"dotenv": "^16.0.3"
}
}
Here is my register.js to register the commands
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const commands = [
{
name: 'hugging-face',
description: 'input images and prompt',
},
];
const rest = new REST({ version: '10' }).setToken(process.env.TOKEN);
(async () => {
try {
console.log('Started refreshing application (/) commands.');
await rest.put(Routes.applicationCommands(process.env.APP_ID), {
body: commands,
});
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
})();
I'm not exactly sure what the issue was, but it seems like register.js isn't running if there aren't any logs and/or was run before changes were made. I would run:
npm install && npm run register && npm run start
'npm install' would reinstall your dependencies, in case it's a versioning issue, while
'npm run register' would run ./discord-slash-bot/register.js to refresh all of the commands.
Hope this helps; cheers!
I am trying to use Request-Promise-Native or Axios but getting error during execution. I am sharing my code. I am using dialogflow inline editior. I also try with post api but not working. I guess somewhere i am doing minor mistake. Please explain also it will help me to learn.
'use strict';
const axios = require('axios');
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
const request = require('request-promise-native');
// this is GET api using axios
function Login(agent) {
const email = agent.parameters.email;
const password = agent.parameters.password;
const baseurl = 'http://demoapi:3000/login/buyerlogin';
var data = {"email" : email,"password": password};
return axios.get(baseurl, { params:
data})
.then(result => {
console.log(result.data);
console.log(`statusCode: ${result.statusCode}`);
agent.add(result.data);
}) }
// This Get API using Request promise native
function Login(agent) {
const email = agent.parameters.email;
const password = agent.parameters.password;
const baseurl = 'http://demoapi:3000/login/buyerlogin';
var data = {"email" : email,"password": password};
var sdata = JSON.stringify(data);
const options = {
method: 'GET',
uri: baseurl,
body: JSON.parse(sdata),
json: true
};
return request(options)
.then(result => {
console.log(result.data);
console.log(`statusCode: ${result.statusCode}`);
agent.add(result.data);
});
}
Package.json file
{
"name": "dialogflowFirebaseFulfillment",
"description": "This is the default fulfillment for a Dialogflow agents using Cloud Functions for Firebase",
"version": "0.0.1",
"private": true,
"license": "Apache Version 2.0",
"author": "Google Inc.",
"engines": {
"node": "10"
},
"scripts": {
"start": "firebase serve --only functions:dialogflowFirebaseFulfillment",
"deploy": "firebase deploy --only functions:dialogflowFirebaseFulfillment"
},
"dependencies": {
"actions-on-google": "^2.2.0",
"firebase-admin": "^5.13.1",
"firebase-functions": "^2.0.2",
"dialogflow": "^1.2.0",
"dialogflow-fulfillment": "^0.6.1",
"request": "^2.88.2",
"request-promise-native": "^1.0.9",
"axios": "^0.21.1"
}
}
Please help me out. Is anything required please let me.
Thank You
index.js
const {GraphQLServer, GrphQLServer, PubSub } = require('graphql-yoga');
const db = require('./db');
const Query = require('./resolvers/Query');
const Mutation = require('./resolvers/Mutation');
const subscription = require('./resolvers/Substription')
const pubsub = new PubSub();
const typeDefs=`
type Query{
me:User!
signlevalue(name:String):String
sum(marks:[Int]):Int!
user:[User]
}
type Mutation{
createUser(id:ID,name:String,email:String):[User]
}
type User{
id:ID
name:String
email:String
age:Int
}
type Subscription{
count:Int
}
`
const resolvers={
Query,
Mutation,
subscription
}
const server= new GraphQLServer({
typeDefs,
resolvers,
context:{
db,
pubsub
}
})
server.start(()=>{
console.log('servr is running on port 4000');
})
Substription.js
const Subscription={
count:{
subscribe(parent,args,{pubsub},info){
let count=0;
setInterval(() => {
count++;
pubsub.publish('count',{
count:count
})
}, 1000);
return pubsub.asynsIterateor('count')
}
}
}
module.exports = Subscription;
package.json
{
"name": "sql",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon src/index.js --ext js,graphql --exec babel-node",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.7.0",
"express": "^4.17.1",
"express-graphql": "^0.11.0",
"graphql": "^15.3.0",
"graphql-yoga": "^1.18.3",
"lodash": "^4.17.20"
}
}
i am a biggner in graphQL word and i dont know what is wrong here because i have defined subsciption in schema but it still gives me error "subscription" defined in resolvers, but not in schema i have searched it but not finding any solution i am following andrew mead course from udemy
your import name is "subscription" (small s) while in your type defination you are using "Subscription"(large s)
use this
const Subscription = require('./resolvers/Substription')
I'm getting the error as "async functions' is only available in es8 (use 'esversion 8')"
I tried putting "esversion:8" in inline code, package.json but its not working out and function is not getting deployed.
Code:
index.js
'use strict';
'use esversion: 8'; //not working
async function getWeather() {
const city = 'Mumbai';
const OPENWEATHER_API_KEY = '<API KEY>';
const response = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${OPENWEATHER_API_KEY}`);
const data = await response.json();
console.log(data);
const { main } = data;
const { temp } = main;
const kelvin = temp;
const celsius = Math.round(kelvin - 273.15);
console.log(celsius);
}
Code package.json
{
"name": "dialogflowFirebaseFulfillment",
"description": "This is the default fulfillment for a Dialogflow agents using Cloud Functions for Firebase",
"version": "0.0.1",
"private": true,
"license": "Apache Version 2.0",
"author": "Google Inc.",
"engines": {
"node": "8"
},
"scripts": {
"start": "firebase serve --only functions:dialogflowFirebaseFulfillment",
"deploy": "firebase deploy --only functions:dialogflowFirebaseFulfillment"
},
"dependencies": {
"actions-on-google": "^2.2.0",
"firebase-admin": "^5.13.1",
"firebase-functions": "^2.0.2",
"dialogflow": "^0.6.0",
"dialogflow-fulfillment": "^0.5.0",
"esversion":"8" //not working
}
}
Error Screenshot
Is there any solution to this or any other way?
I am working on node project, In my project I have two images in the images folder. Now my goal is I have to zip those two images and download. For this I am using this npm zip-downloader.
But I am getting these kind of errors
Error: Cannot find module 'babel-runtime/core-js/object/assign'
This is my code, server.js
const express = require('express');
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');
const multer = require('multer');
const upload = multer({dist:'./uploads'});
const jimp = require('jimp');
const zip = require('file-zip');
const downloader = require('zip-downloader')
app.post('/api/images',upload.single('profilepic'), (req, res) =>{
console.log(req.file)
res.json({'message':'file upload successfully'})
});
jimp.read('images/one.jpeg')
.then(one => {
return morng
.resize(100, 100) // resize
.quality(60) // set JPEG quality
.greyscale() // set greyscale
.write('images/two.jpg'); // save
})
.catch(err => {
console.error(err);
});
zip.zipFile(['images/one.jpeg','images/two.jpg'],'out.zip',function(err){
if(err){
console.log('zip error',err)
}else{
console.log('zip success');
}
})
const assets = [
{
'src': 'images/one.jpeg'
},
{
'src': 'images/two.jpg'
}
];
const options = {
downloadFolderName: 'images',
statusCallback: function(downloadedTillNow){
console.log('Download status:' + ((downloadedTillNow * 100)/assets.length));
},
onComplete : function(downloadedSummary){
console.log('Assets downloaded:' + downloadedSummary.numberOfDownloadedAssets);
console.log('Assets failed:' + downloadedSummary.numberOfFailedAssets);
console.log('Large Assets downloaded(over maxZIPSize):' + downloadedSummary.numberOfLargeUnZippedAssets);
console.log('Number of zip files downloaded:' + downloadedSummary.numberOfDownloadedZIPFiles);
console.log('Array of failed assets:');
console.log(downloadedSummary.failedAssetList);
},
};
downloader(assets, options);
This is package.json file
{
"name": "file",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"file-zip": "^1.0.1",
"files-download-zip": "^3.1.1",
"jimp": "^0.9.3",
"jszip": "^3.2.2",
"multer": "^1.4.2",
"zip-downloader": "^1.0.2"
}
}
Need a solution to overcome this error.
Since you're defining an object const options = {}, all of the properties which are defined inside the bracket {} should follow by :
The error in this case:
SyntaxError: Invalid shorthand property initializer
means you're trying to create a property with invalid syntax.
You can fix it by:
const options = {
downloadFolderName: 'images',
statusCallback: function(downloadedTillNow){
console.log('Download status:' + ((downloadedTillNow * 100)/assets.length));
},
onComplete: function(downloadedSummary){
console.log('Assets downloaded:' + downloadedSummary.numberOfDownloadedAssets);
console.log('Assets failed:' + downloadedSummary.numberOfFailedAssets);
console.log('Large Assets downloaded(over maxZIPSize):' + downloadedSummary.numberOfLargeUnZippedAssets);
console.log('Number of zip files downloaded:' + downloadedSummary.numberOfDownloadedZIPFiles);
console.log('Array of failed assets:');
console.log(downloadedSummary.failedAssetList);
}
};