show object in gcloud app engine console.log - google-app-engine

When using console.log in a node app deploy on app engine, if i console.log an object, it's all written line by line.
I would like to know if it's possible to have it logged in a clean way (cf picture)
this is the result of console.log('connection: ', connection);
Idealy i would like to have my object connection appear like that :
I'm probably missing something there, if anyone can help me clear that it would be awesome ! thanks

To log objects as one entry in stackdriver, I use the client library.[1]
Using[1] this is how my app.js looks:
'use strict';
const express = require('express');
const {Logging} = require('#google-cloud/logging');
const app = express();
const logging = new Logging();
const log = logging.log('projects/[PROJECT-ID/logs/[ANY-LOG-NAME]');
const resource = {type: 'gae_app',
labels: {
'project_id': '[PROJECT-ID]',
'module_id': '[SERVICE-NAME]',
'version_id': '[ANY-VERSION-ID]',
'zone': '[CURRENT-APPENGINE-REGION]'
}
};
const entry = log.entry({resource},"Plain message one");
let dict1 = {"First name": "Jhon",
"Last name": "Smith",
"Age":32,
"Gender": "Male" };
const secondentry = log.entry({resource},{dict1});
app.get('/', (req, res) => {
console.log('Using logging client library...');
log.write([entry,secondentry]);
res.status(200).send('Printing some messages to the console').end();
});
This is my package.json:
{
"name": "node101",
"engines": {
"node": ">=8.0.0"
},
"scripts": {
"start": "node app.js",
"test": "mocha --exit test/*.test.js"
},
"dependencies": {
"express": "^4.16.3",
"#google-cloud/logging": "^7.3.0"
},
"devDependencies": {
"mocha": "^7.0.0",
"supertest": "^4.0.2"
}
}
It is important to configure properly the resource variable, otherwise your log will not appear.
I have used[2][3] to configure the resource variable, you can look at it for more information about other resources.
I deploy using the --version flag; the value of the flag is equal to the one given resource variable in app.js
gcloud app deploy --version='[ANY-VERSION_ID]'
[1] https://cloud.google.com/logging/docs/api/tasks/creating-logs#writing_log_entries
[2] https://cloud.google.com/monitoring/api/resources#tag_gae_app
[3] https://cloud.google.com/logging/docs/reference/v2/rest/v2/MonitoredResource

Related

HTTP 500 error upon deploying application to Google App Engine

I am using Google App Engine to deploy a test application. The deployment works fine and when I point my browser to the following URL, I receive an HTTP 500 error:
https://test-gae-365706.uc.r.appspot.com/
My application code is as follows:
const http = require('http');
const port = 8080;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Do not have an inflated sense of yourself. You are just food for worms.');
});
server.listen(port, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
My app.yaml file is as follows:
runtime: nodejs10
My package.json file is as follows:
{
"name": "app-engine",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "node app.js"
},
"engines": {
"node": "10.x.x"
},
"author": "",
"license": "ISC"
}
When I run glcoud app deploy, I do not get any errors, but when I point my browser to the URL, I get the HTTP 500 error:
Error: Server Error The server encountered an error and could not complete your request. Please try again in 30 seconds.
In the navigation pane, when I go to the Instances page, I see that no instance has been created. Could this be the problem?
Please let me know what is it that I am missing here.
You need a start script in package.json. Based on your test script, it would be something like -
"start": "node app.js"
See a sample Node App from Google
You're using the variable ${hostname} but you haven't defined it. You need to define it and provide a value like you did for port

mongoDB is not working after I deployed my MERN app using Heroku, while the app works fine on my localhost

I am pulling my hair for couple of hours suffering from this issue... :(
The app works fine on my localhost, but mongoDB doesn't seem to be connected to my app.
It keeps gives me a "Type error" and I think it does Not GET a response from mongoDB.
Here's my index.js file in backend directory, and .env file is in the same directory with index.js.
// backend/index.js
const express = require("express");
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const app = express();
const pinRoute = require("./routes/pins");
const userRoute = require("./routes/users");
const path = require("path")
dotenv.config();
app.use(express.json());
const uri = process.env.MONGO_URL;
console.log(uri)
// console.log does show uri.
mongoose
.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
})
.then(() => {
console.log("MongoDB Connected :)");
})
.catch((err) => console.log(err));
app.use("/api/pins", pinRoute);
app.use("/api/users", userRoute);
if (process.env.NODE_ENV === "production") {
app.use(express.static("frontend/build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "../frontend", "build", "index.html"))
})
}
const port = process.env.PORT || 8800;
app.listen(port, () => {
console.log(`Backend server is running at ${port} :)`);
});
and here's my package.json
// this is in the root directory.
{
"name": "backend",
"version": "1.0.0",
"main": "backend/index.js",
"license": "MIT",
"engines": {
"node": "14.15.4",
"yarn": "1.22.10"
},
"scripts": {
"start": "node backend/index.js",
"backend": "nodemon backend/index.js",
"frontend": "cd frontend && yarn start",
"heroku-postbuild": "cd frontend && yarn install && yarn build ",
"build": "cd frontend && yarn build"
},
"dependencies": {
"bcrypt": "^5.0.1",
"dotenv": "^9.0.2",
"express": "^4.17.1",
"mongoose": "^5.12.8",
"nodemon": "^2.0.7"
}
}
This is the error I get ...
1.Try using the environment variable name as a parameter to mongoose.connect and see if it works. You do not need to assign the value to the uri constant as you did so.
mongoose
.connect(process.env.MONGO_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
})
.then(() => {
console.log("MongoDB Connected);
})
.catch((err) => console.log(err));
You could add a route to your base URL that gives you a response when you hit the same.
app.get("/", (req, res) => {
res.send("Default Route Works!");
})
EDIT:
Add this to your app.js below the middleware and whenever you redirect to
http://localhost:PORT/
eg. http://localhost:8080/ GET Request
you should see the message "Default Route Works!" on the screen. Alternatively you can send a GET request to the same end point via an API client like Insomnia, or POSTMAN.
Note: Please change your port number to where it says PORT in the localhost address.

Deployed NextJS over Firebase but getting Error 403 Forbidden

I just deployed my NextJS app over Firebase Hosting and Firebase Functions. After the deployment is successful, I went to the website but I was greeted with this page.
this is my firebase.json
{
"hosting": {
"public": "public",
"ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
"rewrites": [
{
"source": "**",
"function": "nextApp"
}
]
},
"functions": {
"source": ".",
"predeploy": [
"npm install",
"npm run build"
],
"runtime": "nodejs12",
"ignore": [
"**/tests/**",
"**/node_modules/**",
"jest.config.js"
]
}
}
my cloud functions for nextJS
// This file is an entry point for Firebase Function to serve NextJS
const functions = require('firebase-functions');
const { default: next } = require('next');
const dev = process.env.NODE_ENV !== 'production';
const app = next({
dev,
conf: {
distDir: '.next',
future: {
strictPostcssConfiguration: false,
excludeDefaultMomentLocales: true,
webpack5: false,
},
},
});
const handle = app.getRequestHandler();
exports.nextApp = functions.region('asia-southeast2').https.onRequest((req, res) => {
console.log('File: ' + req.originalUrl);
return app.prepare().then(() => handle(req, res));
});
I did check Google Cloud Console and made sure that I've added allUsers to the Cloud Function Invoker role, but it isn't helping.
Sorry, silly me I've figured it out. The issue is because I'm deploying the Cloud Function to asia-southeast2 region but Firebase Hosting only able to access Cloud Functions hosted in us-central1.

Transpiling NextJS for IE 10/11; 'Weakset undefined'

I have a NextJS website I'm building and it's great, except that it does not work in IE 10/11 because some code is not being transpiled correctly. I'm really bad with babel and webpack, and have never had to config them myself before. I've been trying to solve by reading online for two days now, and nothing seems to work for me.
The exact error I get is weakSet is not defined, and it is coming from the common.js file.
Here is my .babelrc file, located in the root of my project.
// .babelrc
{
"presets": ["next/babel"],
"plugins": [
["styled-components", {
"ssr": true,
"displayName": true,
"preprocess": false
}]
]
}
my package.json
{
"name": "bradshouse",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "next",
"build": "next build",
"start": "next start"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"next": "^7.0.2",
"react": "^16.6.0",
"react-dom": "^16.6.0",
"react-pose": "^4.0.1",
"styled-components": "^4.0.2"
},
"devDependencies": {
"babel-plugin-styled-components": "^1.8.0"
}
}
The full repo is here if you're interested in launching it yourself. node modules are excluded, so npm install, then npm run build, then npm run start.
https://github.com/TJBlackman/Brads-House
Thanks for the help! Feel free to just link articles and I'll read them thoroughly! Thanks.
Edit: As a quick fix, I added this polyfill script to the <head> of all my pages, and it still did not fix this issue... Wat?! <script src="https://cdn.polyfill.io/v2/polyfill.min.js"></script>
How to support IE 11 by transpiling node_modules code in NextJS
Original answer found in the ziet/nextjs issues thread (view here). Shout out to joaovieira <3
npm install --save-dev babel-polyfill
create a polyfill.js where ever you want it, and inside that file, import the babel-polyfill like so:
import 'babel-polyfill';
Next, if you do not have a next.config.js file, create it at your root directory. Now update your this file to include the following webpack config. Notice how it's using the polyfill file you just made. Full file example:
module.exports = {
webpack: (config) => {
// Unshift polyfills in main entrypoint.
const originalEntry = config.entry;
config.entry = async () => {
const entries = await originalEntry();
if (entries['main.js']) {
entries['main.js'].unshift('./path_to/polyfills.js'); // <- polyfill here
}
return entries;
};
return config;
}
}
Finally, if you don't have a .babelrc file in your project's root directory, create one. Inside it, use the code below that matches the version of babel you're using.
Babel 7
{
"presets": [
[
"next/babel",
{
"preset-env": {
"useBuiltIns": "usage"
}
}
]
]
}
Babel 6
{
"presets": [
[
"next/babel",
{
"preset-env": {
"targets": {
"browsers": "defaults"
},
"useBuiltIns": true
}
}
]
]
}
That's all I know. I'm not even thinking about IE 10...
Good luck!!
I am using next#9.3 with reflect-metadata, and here is my solution:
/** next.config.js > webpack **/
const pathToPolyfills = './src/polyfills.js'
// Fix [TypeError: Reflect.metadata is not a function] during production build
// Thanks to https://leerob.io/blog/things-ive-learned-building-nextjs-apps#polyfills
// There is an official example as well: https://git.io/JfqUF
const originalEntry = config.entry
config.entry = async () => {
const entries = await originalEntry()
Object.keys(entries).forEach(pageBundleEntryJs => {
let sourceFilesIncluded = entries[pageBundleEntryJs]
if (!Array.isArray(sourceFilesIncluded)) {
sourceFilesIncluded = entries[pageBundleEntryJs] = [sourceFilesIncluded]
}
if (!sourceFilesIncluded.some(file => file.includes('polyfills'))) {
sourceFilesIncluded.unshift(pathToPolyfills)
}
})
return entries
}
/** src/polyfills.js **/
// Other polyfills ...
import 'reflect-metadata'

Failed to construct 'WebSocket': The URL '[object Object]' is invalid

I was trying to make a connection to the websocket and get the data in react router. The connection is not happening and getting error Uncaught SyntaxError: Failed to construct 'WebSocket': The URL '[object Object]' is invalid. in the browser console. Using npm start from the terminal to start the application. It is a simple react router application. Below is the react code where I think problem occurred.
import React from 'react'
export default React.createClass({
getInitialState: function() {
return { value : [],
client : '' };
},
componentWillMount: function() {
client = new WebSocket("ws://localhost:8000/","echo-protocol");
client.onerror = function() {
console.log('Connection Error');
};
client.onopen = function() {
function sendNumber() {
if (client.readyState === client.OPEN) {
var number = Math.round(Math.random() * 0xFFFFFF);
client.send(number.toString());
setTimeout(sendNumber, 1000);
}
}
sendNumber();
};
client.onmessage = function(e) {
this.setState({
value: e.data
});
}.bind(this);
},
componentWillUnmount: function(){
client.close();
},
render: function() {
return (React.createElement("div",null,this.state.value))
}
});
The webpack config file is -
module.exports = {
entry: './index.js',
output: {
filename: 'bundle.js',
publicPath: ''
},
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader?presets[]=es2015&presets[]=react' }
]
}
}
Also, the packge.json file is
{
"name": "react_form",
"version": "1.0.0",
"description": "Sample form that uses React for its rendering",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --inline --content-base . --history-api-fallback"
},
"author": "J",
"license": "ISC",
"dependencies": {
"react": "^0.14.7",
"react-dom": "^0.14.7",
"react-router": "^2.0.0",
"websocket": "^1.0.23"
},
"devDependencies": {
"babel-core": "^6.5.1",
"babel-loader": "^6.2.2",
"babel-preset-es2015": "^6.5.0",
"babel-preset-react": "^6.5.0",
"http-server": "^0.8.5",
"webpack": "^1.12.13",
"webpack-dev-server": "^1.14.1"
}
}
If any other piece of code is required then please let me know. Also, please find the image of the error coming in the console on selecting the route option. What is the exact issue I am not able to get ?
Try this syntax:
const client = new WebSocket("ws://localhost:8000/");
I was debugging the app in various different ways I could. Then I found that there is no problem with the code. Further changed the name of the file from WebSocket to Socket and route name from webSocket to socket in various files and it worked. The problem was with naming the files and including them into the code accordingly.
On your backend side, if you dont have header with key = "Sec-WebSocket-Protocol" and value of one of your protocols, you will always get this error on chrome.
In my case, it was fine with Firefox

Resources