Why this GET request is not working? - node.js

enter image description here
I am doing all this on codeanywhere

That should work. Unless..
Make sure you npm install express
Since your file is named app.js make sure in your package.json file it reads something like this.
Make sure main says app.js not index.js or server.js
{
"name": "stack-test",
"version": "1.0.0",
"main": "app.js",
"license": "MIT",
"dependencies": {
"express": "^4.16.2"
}
}
This will give you an err if something breaks.
var express = require('express');
var app = express();
var port = process.env.PORT || 3000;
app.get('/', function(req, res) {
res.send("Hi there");
})
app.listen(port, (err) => {
if (err) {
console.log(`Error: ${err}`);
} else {
console.log(`App running on port ${port}`);
}
});

Related

Google App Engine adding child_process causes CORS error

I have an express server, which works locally, but when I deploy it to App Engine and send a request I get the response that it has been blocked by CORS policy. If I remove the section where I call exec (and move send response) there is no error.
Why could this be happening?
My code:
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const { exec } = require('child_process');
const app = express();
app.use(bodyParser.json());
app.use(cors());
module.exports = app
app.post("/", (req,res) =>{
console.log("Get from /");
console.log(req.body.data)
//IF I COMMENT EXEC OUT IT WORKS
exec('npx hardhat run scripts/deploy.js --network goerli',
(error, stdout, stderr) => {
if (error !== null) {
console.log(`exec error: ${error}`);
}
else{
res.send("response");
}
})
});
app.listen(8080, () => {
console.log('listening on port 8080');
});
This is my package.json:
{
"name": "hardhat-project",
"devDependencies": {
"#nomiclabs/hardhat-ethers": "^2.0.6",
"ethers": "^5.6.9",
"hardhat": "^2.9.9"
},
"version": "1.0.0",
"description": "smart contract",
"main": "hardhat.config.js",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.18.1",
"firebase-admin": "^11.0.0"
},
"scripts": {
"start": "node src/index.js",
"test": "mocha"
},
"author": "",
"license": "ISC"
}
A screenshot of the error:

Firebase function error - UnsupportedMediaTypeError: unsupported content encoding "utf-8"

I am trying to capture data from an API call and keep getting this error
UnsupportedMediaTypeError: unsupported content encoding "utf-8"
This is my firebase function (nodeJs)
const functions = require("firebase-functions");
const admin = require("firebase-admin");
exports.input = functions.https.onRequest((req, res) => {
console.log(req.body);
res.status(200).send('Success');
});
Your mistake is here: res.status(200).send('Success');
You need to pass json data here is example:
res.status(200).send({success: true, data: { key: "value"}});
So this is how I solved the issue.
In firebase functions this cannot be done, since the header has to be deleted prior to invoking the body parser middleware(this is a workaround). So I had to use Cloud Run for this. I Created a docker image like this.
Docker File
FROM node:16-alpine
WORKDIR /usr/src/app
COPY package.json package*.json ./
RUN npm install --only=production
COPY . .
CMD [ "npm", "start" ]
Index
const express = require('express');
const Firestore = require('#google-cloud/firestore')
const db = new Firestore();
const app = express();
app.use(function (req, res, next) {
// remove invalid header
delete req.headers['content-encoding'];
next();
});
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.log(`SMS in API listening on port ${port}`);
});
app.post('/', async (req, res) => {
console.log("SMS IN " + req.body.phone_number + " - " + req.body.message);
await db.collection('sms-in').doc().set({
phone_number: req.body.phone_number,
shortcode: req.body.shortcode,
message: req.body.message,
});
res.json('Success');
});
app.get('/', async (req, res) => {
res.json('I have nothing to give you.');
})
package.json
{
"name": "smsin",
"version": "1.0.0",
"description": "Description here",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"author": "Author name here",
"license": "ISC",
"dependencies": {
"#google-cloud/firestore": "^5.0.1",
"express": "^4.17.1"
}
}

I am trying to deploy a simple react and nodejs application using heroku but after deployment it is just showing hello world, unable to figure it out?

According to online tutorials i ran npm run build in the react app and then pasted the build folder in the server directory but i think it is just serving the server side, i am unable to figure out the problem , please help me what is the error in its deployment
My index.js
const express = require("express");
const app = express();
const cors = require("cors");
const mongoose = require("mongoose");
const path = require("path")
const { MONGODB } = require("./config");
const model = require("./models/user");
const router = require("./Routes/auth");
const PORT = process.env.PORT || 8000;
/***********************************config ************************* */
mongoose.connect(MONGODB, { useNewUrlParser: true, useUnifiedTopology: true });
mongoose.connection.on("connected", () => {
console.log("connected to mongoDb");
});
/********************model imports ***************************/
const User = require("./models/user");
const Post = require("./models/post");
/********************************middlewares**************************** */
app.use(express.json());
app.use(cors());
app.use(router);
app.use(require("./Routes/posts"));
app.use(require("./Routes/user"));
/****code related to production of app***** */
app.use(express.static(path.join(__dirname, 'build')));
app.get('/*', (req, res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
/**********************listening on server *********************** */
app.listen(PORT, (err) => {
if (err) {
return console.log(`Error: ${err}`);
}
console.log(`server running on port: ${PORT}`);
});
my package.json - server
{
"name": "instagram-clone",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"cors": "^2.8.5",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.12.4",
"nodemon": "^2.0.7",
"path": "^0.12.7"
}
}
Github link: https://github.com/dhruv354/insta-app.git

404 on deploy using ExpressJS and React

Project works as intended locally. To run locally, I currently run the command npm run start in both the project root and the client root concurrently.
I am working to create a simple application using Express and Create React App. Despite a successful build and no errors in my Heroku logs, my deploy shows a blank page that says "Not Found" and has a 404 error in the chrome console.
File directory:
client
> src
-> components
-> app.js
> package.json
routes
> tweets.js
index.js
package.json
Root package.json:
{
"name": "newStock",
"version": "1.0.0",
"description": "",
"main": "index.js",
"engines": {
"npm": "6.x",
"node": "12.x"
},
"scripts": {
"start": "node index.js",
"heroku-postbuild": "cd client && npm install && npm run build",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"password-generator": "^2.2.3",
"socket.io": "^2.3.0",
"socket.io-client": "^2.3.0",
"twitter": "^1.7.1"
}
}
Root index.js:
const express = require("express");
const http = require("http");
const socketio = require("socket.io");
const path = require("path");
const bodyParser = require("body-parser");
const app = express();
require("dotenv").config({ path: "./.env" });
require("./routes/tweets.js")(app, io);
const server = http.createServer(app);
const io = socketio(server);
//middleware
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, "client/build")));
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname + "/client/build/index.html"));
});
const port = process.env.PORT || 3001;
console.log(`Password generator listening on ${port}`);
server.listen(port, () => {
console.log("server is up");
});
Root routes/tweets.js:
const Twitter = require("twitter");
module.exports = (app, io) => {
let twitter = new Twitter({
consumer_key: process.env.TWITTER_CONSUMER_KEY,
consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
});
let socketConnection;
let twitterStream;
app.locals.searchTerm = "cake"; //Default search term for twitter stream.
app.locals.showRetweets = false; //Default
/**
* Resumes twitter stream.
*/
const stream = () => {
console.log("Resuming for " + app.locals.searchTerm);
twitter.stream(
"statuses/filter",
{ track: app.locals.searchTerm },
stream => {
stream.on("data", tweet => {
sendMessage(tweet);
});
stream.on("error", error => {
console.log(error);
});
twitterStream = stream;
}
);
};
/**
* Sets search term for twitter stream.
*/
app.post("/setSearchTerm", (req, res) => {
let term = req.body.term;
app.locals.searchTerm = term;
twitterStream.destroy();
stream();
console.log(req.body.term);
});
/**
* Pauses the twitter stream.
*/
app.post("/pause", (req, res) => {
console.log("Pause");
console.log(req.body.term);
twitterStream.destroy();
});
/**
* Resumes the twitter stream.
*/
app.post("/resume", (req, res) => {
console.log(req.body.term);
console.log("Resume");
stream();
});
//Establishes socket connection.
io.on("connection", socket => {
socketConnection = socket;
stream();
socket.on("connection", () => console.log("Client connected"));
socket.on("disconnect", () => console.log("Client disconnected"));
});
/**
* Emits data from stream.
* #param {String} msg
*/
const sendMessage = msg => {
if (msg.text.includes("RT")) {
return;
}
socketConnection.emit("tweets", msg);
};
};
All I needed to do was reset the git cache of my client directory as it wasn't even being added to git because of this. I only noticed when I uploaded the repo to GitHub to save it for another day.
wow.

Can't figure out why Heroku website is outputting `cannot GET /` message

so, it just says 'cannot GET /' everytime i try to view my app
here is the code
server.js
//Import requiered packages
const express = require('express');
const {Client} = require('pg');
//Create the conection to the postgres server
const client = new Client({
connectionString: process.env.DATABASE_URL
});
client.connect();
//Create the express app
const bodyParser = require('body-parser');
const app = express();
// parse application/json
app.use(bodyParser.json());
//Handle a post request at /query
app.post('/query', (req, res) => {
res.setHeader('Content-Type', 'application/json');
console.log("Receiving request");
if(req.body.query) {
console.log(req.body.query);
client.query(req.body.query, (err, r) => {
if (err) throw err;
rows = [];
for(let row of r.rows){
rows.push(row);
}
response = JSON.stringify(rows);
console.log(response);
res.end(response);
});
}
});
const port = process.env.PORT || 8080
//Start listening
const server = app.listen(port, function () {
console.log("App listening at ${host}")
});
package.json
{
"name": "haha",
"description": "joseph = obesity > lawa",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"dependencies": {
"express": "4.x.x",
"pg": "7.x.x",
"body-parser": "1.18.x"
}
}
I literally have no clue what's wrong and theres almost no erroirs in the CLI.
The errors in the CLI are basically irrelevant to this, as even if tehre are no errors im still presented with the 'cannot GET /' message
please help me :(

Resources