I'm getting this error massage when I run my server.js file.
Error Message:
let films = await response.data.films.map(film =>{
^^^^^
SyntaxError: await is only valid in async function
at new Script (vm.js:79:7)
at createScript (vm.js:251:10)
at Object.runInThisContext (vm.js:303:10)
at Module._compile (internal/modules/cjs/loader.js:657:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
at startup (internal/bootstrap/node.js:283:19
app.get('/api/popular/movies', async (req, res, next)=> {
axiosInstance.get(`filmsNowShowing/`).then(response=> {
console.log(response.data.films)
let films = await response.data.films.map(film =>{
return {
id:film.film_id,
name:film.film_name,
textLong:film.synopsis_long,
picimage:film.images.poster
}
})
res.status(200).json(films);
}).catch(err => {
console.log(err);
});
});
You missed an async inside the .then(response => { ... })
app.get('/api/popular/movies', async (req, res, next)=> {
await axiosInstance.get(`filmsNowShowing/`).then(async response => {
console.log(response.data.films)
let films = await response.data.films.map(film =>{
return {
id:film.film_id,
name:film.film_name,
textLong:film.synopsis_long,
picimage:film.images.poster
}
})
res.status(200).json(films);
}).catch(err => {
console.log(err);
});
});
Related
I am new to coding I was just making a simple ping command when I went to run it I got this error I have tried fixing it but I can't seem to find the problem please help me! I have been following this video (https://www.youtube.com/watch?v=6IgOXmQMT68&list=PLv0io0WjFNn9LDsv1W4fOWygNFzY342Jm&index=1).
ping.js:
const { SlashCommandBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Return my ping!'),
async execute(interaction, client) {
const messsage = await interaction.deferReply({
fetchReply: true
});
const newMessage = `API Latency: ${client.ws.ping}\nClient Ping: ${message.createdTimestamp - interaction.createdTimestamp}`
await interaction.editReply({
content: newMessage
});
}
}
handleEvents.js:
const fs = require("fs");
module.exports = (client) => {
client.handleEvents = async () => {
const eventFolders = fs.readdirSync(`./src/events`);
for (const folder of eventFolders) {
const eventFiles = fs
.readdirSync(`./src/events/${folder}`)
.filter((file) => file.endsWith(".js"));
switch (folder) {
case "client":
for (const file of eventFiles) {
const event = require(`../../events/${folder}/${file}`);
if (event.once)
client.once(event.name, (...args) =>
event.execute(...args, client)
);
else
client.on(event.name, (...args) =>
event.execute(...args, client)
);
}
break;
default:
break;
}
}
};
};
interactionCreate.js:
module.exports = {
name: "interactionCreate",
async execute(interaction, client) {
if (interaction.isChatInputCommand()) {
const { commands } = client;
const { commandName } = interaction;
const command = commands.get(commandName);
if (!command) return;
try {
await command.execute(interaction, client);
} catch (error) {
console.error(error);
await interaction.reply({
content: `Something went wrong while executing this command...`,
ephemeral: true,
});
}
}
},
};
Error:
TypeError: command.execute is not a function
at Object.execute (C:\Users\mikay\OneDrive\Desktop\v14 Bot\src\events\client\interactionCreate.js:11:23)
at Client.<anonymous> (C:\Users\mikay\OneDrive\Desktop\v14 Bot\src\functions\handlers\handleEvents.js:20:23)
at Client.emit (node:events:513:28)
at InteractionCreateAction.handle (C:\Users\mikay\OneDrive\Desktop\v14 Bot\node_modules\discord.js\src\client\actions\InteractionCreate.js:81:12)
at Object.module.exports [as INTERACTION_CREATE] (C:\Users\mikay\OneDrive\Desktop\v14 Bot\node_modules\discord.js\src\client\websocket\handlers\INTERACTION_CREATE.js:4:36)
at WebSocketManager.handlePacket (C:\Users\mikay\OneDrive\Desktop\v14 Bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:352:31)
at WebSocketShard.onPacket (C:\Users\mikay\OneDrive\Desktop\v14 Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:480:22)
at WebSocketShard.onMessage (C:\Users\mikay\OneDrive\Desktop\v14 Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:320:10)
at WebSocket.onMessage (C:\Users\mikay\OneDrive\Desktop\v14 Bot\node_modules\ws\lib\event-target.js:199:18)
at WebSocket.emit (node:events:513:28)
Remove await on 11
commands.set(command.data.name, commands);
remove s from the last command
Server is starting at 8080
GET / 304 - - 1.952 ms
(node:6139) UnhandledPromiseRejectionWarning: MongooseServerSelectionError: bad auth Authentication failed.
at new MongooseServerSelectionError (/Users/abc/Desktop/success/node_modules/mongoose/lib/error/serverSelection.js:22:11)
at NativeConnection.Connection.openUri (/Users/abc/Desktop/success/node_modules/mongoose/lib/connection.js:808:32)
at Mongoose.connect (/Users/abc/Desktop/success/node_modules/mongoose/lib/index.js:333:15)
at Object. (/Users/abc/Desktop/success/pages/server.js:18:10)
at Module._compile (internal/modules/cjs/loader.js:1158:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
(node:6139) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:6139) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
GET / 304 - - 0.320 ms
GET / 304 - - 0.236 ms
GET / 304 - - 0.210 ms
When I run Port 8080 for my serverjs, the file works but no data gets into my mongoDB and I get the above error on my terminal. I only have a server.js page and an index.tsx page. My index.tsx page has a simple Hello world and I am trying to connect Mongodb using the server.js file.
Here is my code:
import express from 'express';
import { connect, connection, Schema as _Schema, model } from 'mongoose';
import morgan from 'morgan';
import path from 'path';
const app = express();
const PORT = process.env.PORT || 8080;
//Success
const MONGODB_URI = 'mongodb+srv://xxxxxxxxxx';
mongoose.connect(MONGODB_URI || 'mongodb://localhost/success', {
useNewUrlParser: true,
useUnifiedTopology: true
});
mongoose.connection.on('connected', () => {
console.log('Mongoose is connected');
})
//Schema
const Schema = _Schema;
const BlogPostSchema = new Schema({
title: String,
body: String,
date: {
type: String,
default: Date.now()
}
});
//Model
const BlogPost = model('BlogPost', BlogPostSchema);
//Saving data to our mongoDB
const data = {
title: 'welcome',
body: 'first post'
};
const newBlogPost = new BlogPost(data);
newBlogPost.save((error) => {
if (error) {
console.log("Somethign happened");
} else {
console.log("data saved");
}
});
//HTTP request logger
app.use(morgan('tiny'));
//Routes
app.get('/', (req, res) => {
const data = {
username: 'caa',
age: 5
};
res.json(data);
});
app.get('/api/name', (req, res) => {
const data = {
username: 'caa',
age: 5
};
res.json(data);
});
app.listen(PORT, console.log(`Server is starting at ${PORT}`));
I think it's because mongoose.connect is asynchronous(not very clear from the documentation). Try putting your code within the "connected" event and see if it works:
mongoose.connection.on('connected', () => {
console.log('Mongoose is connected');
//Schema
const Schema = _Schema;
const BlogPostSchema = new Schema({
title: String,
body: String,
date: {
type: String,
default: Date.now()
}
});
//Model
const BlogPost = model('BlogPost', BlogPostSchema);
//Saving data to our mongoDB
const data = {
title: 'welcome',
body: 'first post'
};
const newBlogPost = new BlogPost(data);
newBlogPost.save((error) => {
if (error) {
console.log("Somethign happened");
} else {
console.log("data saved");
}
});
//HTTP request logger
app.use(morgan('tiny'));
//Routes
app.get('/', (req, res) => {
const data = {
username: 'caa',
age: 5
};
res.json(data);
});
app.get('/api/name', (req, res) => {
const data = {
username: 'caa',
age: 5
};
res.json(data);
});
app.listen(PORT, console.log(`Server is starting at ${PORT}`));
})
const express=require('express');
const mongoose=require('mongoose');
const morgan=require('morgan');
const path=require('path');
const app = express();
const PORT = process.env.PORT || 8080;
mongoose.connect('mongodb://localhost/SUCCESS', {
useNewUrlParser: true,
useUnifiedTopology: true
});
mongoose.connection.on('connected', () => {
console.log('Mongoose is connected');
})
//HTTP request logger
app.use(morgan('tiny'));
//Routes
app.get('/', (req, res) => {
const data = {
username: 'caa',
age: 5
};
res.json(data);
});
app.get('/api/name', (req, res) => {
const data = {
username: 'caa',
age: 5
};
res.json(data);
});
app.listen(PORT, console.log(`Server is starting at ${PORT}`));
node pages/server.js
Server is starting at 8080
(node:6253) UnhandledPromiseRejectionWarning: MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
at new MongooseServerSelectionError (/Users/Abc/Desktop/success/node_modules/mongoose/lib/error/serverSelection.js:22:11)
at NativeConnection.Connection.openUri (/Users/Abc/Desktop/success/node_modules/mongoose/lib/connection.js:808:32)
at Mongoose.connect (/Users/Abc/Desktop/success/node_modules/mongoose/lib/index.js:333:15)
at Object.<anonymous> (/Users/Abc/Desktop/success/pages/server.js:18:10)
at Module._compile (internal/modules/cjs/loader.js:1158:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
(node:6253) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:6253) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I had the same issue. Please update your code like this.
mongoose.connect("mongodb://127.0.0.1:27017/SUCCESS",{
useCreateIndex:true,
useNewUrlParser: true,
useUnifiedTopology: true}).then(()=> {
console.log('Database Successfully Connected')},error =>{
console.log(error)})
As next step,
Go to your Task Manager
Services
Start 'MongoDB'
Hope this will work.
// Seems like you did not define the default port of mangoose, Please refer below code
const mongoose = require('mongoose');
const db = "mongodb://localhost:27017/SUCCESS";
mongoose.connect(db, {
useCreateIndex:true,
useUnifiedTopology:true,
useNewUrlParser:true
}).then( () => {
console.log("Connected To Mongo Db DataBase");
}).catch((err) => {
console.log("DataBase Connection Error " + err);
})
I know I'm super late but this should fix it.
const db = mongoose.connect("mongodb://localhost/swag-shop",
{
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
}).then(() => {
console.log("Connected To Mongo Db DataBase");
}).catch((err) => {
console.log("DataBase Connection Error " + err);
});
then go to your powershell in windows or terminal in mac and type 'Mongod' and then create another tab in your terminal or open a another window of powershell and then type 'Mongo' and this should fix your problem.
Hi everyone i try to pass some images to my firebase with Functions but when i deploy firebase(with cli firebase deploy)inside my terminal i got an error and the deploy abort.
Apparently the error say my require inside function/index.js is not a function (line 9 col 45) but the gcconfig was do with the right method for me.
I want to correctly deploy firebase from CLI.
The error from cli firebase deploy i got on my terminal:
Error: Error occurred while parsing your function triggers.
TypeError: require(...) is not a function
at Object.<anonymous> (/Users/luca/Code/Code_Taff/Benibla/bnblproto/functions/index.js:9:45)
at Module._compile (internal/modules/cjs/loader.js:707:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:718:10)
at Module.load (internal/modules/cjs/loader.js:605:32)
at tryModuleLoad (internal/modules/cjs/loader.js:544:12)
at Function.Module._load (internal/modules/cjs/loader.js:536:3)
at Module.require (internal/modules/cjs/loader.js:643:17)
at require (internal/modules/cjs/helpers.js:22:18)
at /usr/local/lib/node_modules/firebase-tools/lib/triggerParser.js:15:15
at Object.<anonymous> (/usr/local/lib/node_modules/firebase-tools/lib/triggerParser.js:53:3)
function/index.js:
const functions = require('firebase-functions');
const cors = require('cors')({origin: true});
const fs = require('fs');
const UUID = require("uuid-v4");
const gcconfig = {
projectId: "beniblaproto",
keyFilename: "beniblaproto.json"
};
const gcs = require("#google-cloud/storage")(gcconfig);
exports.storeImage = functions.https.onRequest((request, response) => {
return cors(request, response, () => {
const body = JSON.parse(request.body);
fs.writeFileSync("/tmp/uploaded-image.jpg", body.image, "base64", err => {
console.log(err);
return response.status(500).json({error: err});
});
const bucket = gcs.bucket("beniblaproto.appspot.com");
const uuid = UUID();
return bucket.upload(
"/tmp/uploaded-image.jpg",
{
uploadType: "media",
destination: "/events/" + uuid + ".jpg",
metadata: {
metadata: {
contentType: "image.jpg",
firebaseStorageDownloadTokens: uuid
}
}
},
(err, file) => {
if (!err) {
response.status(201).json({
imageUrl: "https://firebasestorage.googleapis.con/v0/b" +
bucket.name +
"/o/" +
encodeURIComponent(file.name) +
"?alt=media&token=" +
uuid
});
} else {
console.log(err);
response.status(500).json({error: err});
}
}
);
});
});
if someone can explain me where and for what i fail.
Thank you all have a good day
Firstly you need to import {Storage} of library;
const {Storage} = require("#google-cloud/storage");
after that you need to take an instance with your configuration object;
const gcs = new Storage(gcconfig);
So the title is pretty descriptive, the error i'm getting is:
actions.js:392 Uncaught (in promise) TypeError: (0 , _reactRouterDom.push) is not a function
at _callee6$ (webpack:///./src/app/Army/store/actions.js?:392:49)
at tryCatch (http://localhost:8001/vendor.js:152705:40)
at Generator.invoke [as _invoke] (http://localhost:8001/vendor.js:152943:22)
at Generator.prototype.(anonymous function) [as next] (http://localhost:8001/vendor.js:152757:21)
at step (webpack:///./src/app/Army/store/actions.js?:22:191)
at eval (webpack:///./src/app/Army/store/actions.js?:22:361)
at <anonymous>
Just a bit of background, I'm using import 'babel-polyfill'; to do a asyn/await transpiling and my action looks like this:
export const update = (Id, Data, publish) => async (dispatch) => {
try {
dispatch({
type: BA_UPDATING,
payload: { Id },
});
const lib = await client.then(bfn => bfn);
const response = await lib.getArmy(null, Data.type, Id, { ...Data, publish });
dispatch({
type: BA_UPDATED,
payload: { Id, publish, response },
});
dispatch(push('/Army')); // ERROR.
} catch (error) {
dispatch({
type: BA_ERROR,
payload: {
actions: 'update',
Id,
},
});
}
};
react-router-dom v4.1.1