phantomjs unable to open local file - phantomjs-node

I am able to get the content of http://example.com but not the index.html which is in my code with phantomjs. I see the filePath is correct.
'use strict';
const express = require('express');
const phantom = require('phantom');
const path = require('path');
// Constants
const PORT = 8888;
const HOST = '0.0.0.0';
// App
const app = express();
app.get('/', (req, res) => {
(async function() {
const instance = await phantom.create();
const page = await instance.createPage();
await page.on('onResourceRequested', function(requestData) {
console.info('Requesting', requestData.url);
});
const status = await page.open(getFileUrl('index.html'));
const content = await page.property('content');
console.log(content);
await instance.exit();
})();
});
function getFileUrl(str) {
var pathName = path.resolve( str );
if (pathName[0] !== "/") {
pathName = "/" + pathName;
}
return encodeURI("file://" + pathName);
};
app.listen(PORT, HOST);
console.log(`Running on http://${HOST}:${PORT}`);
Output
Running on http://0.0.0.0:8888
Requesting file:///home/codex/code/target-data-app/index.html
<html><head></head><body></body></html>

Related

i want to connect node js app with mongodb in windows pc but am having a problem connecting

this is the problem on the image
(https://i.stack.imgur.com/amXj4.png)(https://i.stack.imgur.com/amXj4.png)
const express = require("express");
const app = express();
const MongoClient = require("mongodb").MongoClient;
const assert = require("assert");
const url = "mongodb://localhost:27017";
const dbname = "myff";
const client = new MongoClient(url);
client.connect(function(err){
assert.equal(null, err);
console.log("success");
const db = client.db(dbname);
client.close();
});
app.listen(3000, function(){
console.log("3000");
});

Why axios doesn't work with static nodejs server?

I'm having trouble getting my axios .get in production with React.
I created a nodeJS server with express to render my react page each time I want to refresh my page. That work.
But the problem is that it block my axios .get(). So, my page show normaly without the data I normaly get in dev mode.
BackEnd => server.js with sequelize module to manage my database
const express = require('express');
const app = express();
const cors = require('cors');
const path = require('path');
app.use(express.json());
app.use(cors());
const db = require('./models');
app.use(express.static(path.join(__dirname, 'build')));
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
const governmentCreateRouter = require('./routes/GovernmentCreate');
app.use("/governmentCreate", governmentCreateRouter);
db.sequelize.sync().then(() => {
app.listen();
});
BackEnd => GovernmentCreate.js
const express = require('express');
const router = express.Router();
const { GovernmentCreate } = require('../models');
router.get("/", async (req, res) => {
const listOfGovernments = await GovernmentCreate.findAll({
include: {all: true}
});
res.json(listOfGovernments);
});
FrontEnd => Part of code inside my GouvernmentWall.js that is called with url https://www.mon-gouvernement.fr/gouvernement-galerie
const [governmentList, setGovernmentList] = useState([]);
axios.get(`https://www.mon-gouvernement.fr/GovernmentCreate`)
.then((res) => {
console.log(res.data);
const resData = res.data;
setGovernmentList(sortResData);
}).catch((err) => {
console.log(err);
});
After multi-searching I'm thinking that the problem come from these lines in my server.js :
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
But if I remove it, when I try to refresh my page I'm getting a white page diplay Cannot GET /gouvernement-galerie.
So I'm stocking with this issu. I need your help to move forward.
Problem solve !
As #jonrsharpe mentioned, I have to switch my .get('/*' to the bottom of my routes. My server.js look like :
const express = require('express');
const app = express();
const cors = require('cors');
const path = require('path');
app.use(express.json());
app.use(cors());
const db = require('./models');
app.use(express.static(path.join(__dirname, 'build')));
//************************************************
// ROUTES
//************************************************
const governmentCreateRouter = require('./routes/GovernmentCreate');
app.use("/governmentCreate", governmentCreateRouter);
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
db.sequelize.sync().then(() => {
app.listen();
});

I am trying to store my node rest api data to mongodb atlas. But getting insertion errors

I am trying to register the user to mongodb atlas for registration and login but i am geting an error 404.
here is full link to mycode
https://github.com/badrinathareddyr/falcon.git
server.js file
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const authRoute = require('../backend/routes/auth')
//connect to database
dotenv.config({ path: __dirname + '/.env' });
mongoose.connect(
process.env[DB_CONNECT], { useNewUrlParser: true }, () =>
console.log('connected to db!')
);
//Middleware
app.use(express.json());
//middlewareroutes
app.use('/register', authRoute);
app.listen(3000, () => console.log('server up and running'));
auth.js file
var express = require('express');
const router = express.Router();
const User = require('../models/User');
const bcrypt = require('bcryptjs');
router.post('/register', function (req, res) {
if (!req.body.email || !req.body.password) {
res.json({ success: false, msg: 'Please pass email and password.' });
} else {
var newUser = new User({
email: req.body.email,
password: req.body.password
});
// save the user
newUser.save(function (err) {
if (err) {
return res.json({ success: false, msg: 'Email already exists.' });
}
res.json({ success: true, msg: 'Successful created new user.' });
});
}
});
module.exports = router;
It's because of process.env.DB_CONNECT in your code is undefined. Change line 5 of your src/backend/server.js file like below:
const dotenv = require('dotenv').config({ path: __dirname + '/.env' });
then comment dotenv.config()
and copy .env to src/backend/.
Or change line 10 or the file like this:
dotenv.config({ path: __dirname + '/.env' });
You have const User = require('../models/User'); two time in backend/routes/auth.js. Comment line 9. It will give you error.
I fixed it and created pull request in github. Merge it.

Unable to fetch data from mongodb using expressjs

const express = require('express');
const bodyParser = require('body-parser');
const mongodb = require('mongodb');
const app = express();
const cors = require('cors');
app.use(bodyParser.json());
app.use(cors());
const MongoClient = mongodb.MongoClient;
const url = "mongodb://localhost:27017/recart";
app.get("/", (req, res) => {
MongoClient.connect(url,{ useNewUrlParser: true }, async (err, db) => {
if (err) throw err;
var dbo = db.db("recart");
var result = await dbo.collection("users").find()
res.json(result.data)
});
})
app.listen(3001, ()=> {
console.log('App is running on port 3001');
})
Here I am trying to fetch data from mongodb using expressjs,
but in my browser nothing is coming.
No data is coming. But in my database there are documents.
Please have a look
const url = "mongodb://localhost:27017/recart";
Do you really need to provide collection's name here?
You can try:
const mongoUrl = 'mongodb://localhost:27017/'
const MongoClient = require('mongodb').MongoClient
app.get('/', async (req, res) => {
const client = await MongoClient.connect(mongoUrl, {
useNewUrlParser: true
})
const db = client.db("database_name")
const data = await db.collection("collection_name").find().toArray()
res.json(data)
}),

How to use mockgoose (or any other db mocking) in express app integration test

Using mockgoose in a simple unit test is quite straight-forward. However I'm a bit fuzzy as to how one would go about using mockgoose or other mocking solutions in an acceptance or integration test.
Given a simple express/MongoDB app like the following:
/*app.js*/
const express = require('express')
const app = express()
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var greetingSchema = mongoose.Schema({
greeting: String
});
var Greeting = mongoose.model('Greeting', greetingSchema);
app.get('/', function (req, res) {
Greeting.find({greeting: 'Hello World!'}, function (err, greeting){
res.send(greeting);
});
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
and a simple integration test like this:
/*test.js*/
const app = require('app.js');
const request = require('supertest');
it('sends "Hello World!" on the response body', (done) => {
request(app)
.get('/')
.expect(200, 'Hello World!', done);
});
});
By using the actual app in the request, we are connecting to the app's database ('mongodb://localhost/test'). How then can one use mockgoose, or any other solution, to mock the MongoDB database and still run an integration test like the one shown above?
I had the same problem as you. In my case, I solved using chai + chai-http and breaking the db connection and app in different files:
db.js:
const mongoose = require('mongoose');
const config = require('../../config');
mongoose.Promise = global.Promise;
mongoose.set('debug', process.env.DEBUG != undefined);
function open(){
return new Promise((resolve, reject) => {
if(process.env.DEBUG != undefined) {
let Mockgoose = require('mockgoose').Mockgoose;
let mockgoose = new Mockgoose(mongoose);
mockgoose.helper.setDbVersion("** your mongodb version **");
mockgoose.prepareStorage().then(function() {
mongoose.connect(config.db_test, (err, res) => {
if (err) return reject(err);
resolve();
});
}).catch(reject);
}else{
mongoose.connect(config.db, (err, res) => {
if (err) return reject(err);
resolve();
});
}
});
}
function close(){
return mongoose.disconnect();
}
module.exports = { close, open };
app.js:
const express = require('express');
const bodyParser = require('body-parser');
const api = require('./routes');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use('/api', api);
module.exports = app;
test.js (for test):
const chai = require('chai');
const chaiHttp = require('chai-http');
const expect = chai.expect;
const conn = require('./../utils/db'); // <-- db.js
const app = require('../../app'); // <-- app.js
chai.use(chaiHttp);
describe('# Test', function(){
before(function(done) {
conn.open().then(() => done()).catch(done);
});
after(function(done){
conn.close().then(() => done()).catch(done);
});
it(`test something`, function(done){
chai.request(app) // <-- pass the app here
.get('/path/to/test')
.then((res) => {
// expects
done();
})
.catch((err) => {
done(err);
});
});
});
index.js (for development or production):
const conn = require('./utils/db'); // <-- db.js
const app = require('./app'); // <-- app.js
const config = require('./config');
conn.open().then(() => {
app.listen(config.port, () => {
// OK!
});
});
I hope it works for you or anyone.