Deploying node-react app in Heroku - fetch doesn't work - reactjs

I'm trying to deploy a small react app that fetches data mlab - by a node api... locally it's working - when doing fetch - it's returns data - but when deploying to heruko - i get no data back from the Api... i'm newbie to react/node so i must have done something wrong....
Here is the api :
var express = require('express');
var cors = require('cors')
var app = express();
var morgan = require('morgan');
app.use(morgan('dev'));
var port = process.env.PORT || 3007;
var mongoose = require('mongoose');
mongoose.connect('mongodb://ggg:gggg#ds235418.mlab.com:35418/redux-form');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("DB connection alive");
});
var User = require('./model/user');
var Message = require('./model/message');
var router = express.Router();
app.get('/messages',function(req, res) {
Message.find(function(err, messages) {
if (err)
res.send(err);
res.json(messages);
});
});
app.listen(port);
console.log('Magic happens on port ' + port);
And here is the redux action - from the react app
export function getMessages() {
const request = fetch(`http://localhost:3007/messages`, { method: 'GET' })
.then(response => response.json());
return {
type: 'GET_MESSAGES',
payload: request
}
}

Related

"TypeError: Contact is not a constructor" when I check post json data in Postman

When I run node app.js it works, and does not give any error. But when I route localhost:3000/api/contact and post json to check via Postman it gives that error.
I have seen some other releted question but cannot fiqure out.
Here is my app.js
//importing modules
var express = require('express');
var mongoose = require('mongoose');
var bodyparser = require('body-parser');
var cors = require('cors');
var path = require('path');
var app = express();
const route = require('./routes/route');
//connect to mongodb
mongoose.connect('mongodb://localhost:27017/contactlist');
//connection on
mongoose.connection.on('connected',()=>{
console.log('Database connected');
});
mongoose.connection.on('error',(err)=>{
if(err)
{
console.log('Error in database'+err);
}
});
//path port
const port = 3000;
//adding middleware
app.use(cors());
//body-parser
app.use(bodyparser.json());
//static path
app.use(express.static(path.join(__dirname,'public')));
//add route
app.use('/api',route);
//testing server
app.get('/',(req,res)=>{
res.send('foobar');
});
app.listen(port,()=>{
console.log('server is started at port:'+port);
});
Here is my route.js
const express = require('express');
const router = express.Router();
const Contact = require('../models/contacts');
//get data
router.get('/contacts', (req, res, next)=>{
Contact.find(function(err, contacts){
res.json(contacts);
});
});
//add data
router.post('/contact',(req, res, next)=>{
let newContact = new Contact({
first_name: req.body.first_name,
last_name: req.body.last_name,
phone_num: req.body.phone_num
});
newContact.save((err, contact)=>{
if(err)
{
res.json({msg: 'Failed to add contact'});
}
else
{
res.json({msg: 'Contact add succesfuly'});;
}
});
});
//delete data
router.delete('/contact/:id', (req, res, next)=>{
Contact.remove({_id: req.params.id}, function(err, result){
if(err)
{
res.json(err);
}
else
{
res.json(result);
}
});
});
module.exports = router;
I am a new node js learner. I cant understand what is the problem please help me. Thanks in advance!
Take a look at the code below:
// your schema and model
// should look similar to below
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
var ContactSchema = new Schema({
first_name: String,
last_name: String,
phone_num: String
});
const Contact = mongoose.model('Contact', ContactSchema);
module.exports = Contact;
Maybe you forgot to use mongoose.model?

Node Js get post data as json key

NodeJS File server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var moment = require('moment');
var http = require('http');
var jwt = require('jsonwebtoken');
var config = require('./config');
var User = require('./app/models/user');
var port = process.env.PORT || 8080;
mongoose.connect(config.database);
app.set('superSecret', config.secret);
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
app.post('/onboardAuthentication', function(req, res) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
res.setHeader('contentType', 'application/x-www-form-urlencoded;charset=utf-8;');
res.json(req.body);
});
var server = http.createServer(app);
server.listen(port);
console.log('Magic happens at http://localhost:' + port);
Angular API Hit Code where Front side API hit
var serviceRoot='http://localhost:8080/onboardAuthentication';
var deferred=$q.defer();
var req = {
method: 'POST',
url: serviceRoot,
data: { key: 'value' },
contentType: 'application/x-www-form-urlencoded;charset=utf-8;'
};
$http(req).then(goodResponse,badResponse);
return deferred.promise;
function goodResponse(response)
{
console.log("Good response");
console.log(response);
}
function badResponse(response)
{
console.log("Bad response");
console.log(response.data);
}
It print result in this formate, it make post data as key and value is blank, but i want to access post data in json format using body-parsar node js.
{"key":"value"}: ""
If you want to send simple text/ ASCII data, then x-www-form-urlencoded will work,
by default angular will send application/json to the server.
var req = {
method: 'POST',
url: serviceRoot,
data: { key: 'value' },
// comment this line, you don't need it
//contentType: 'application/x-www-form-urlencoded;charset=utf-8;'
};

When use body-parser module in my app , get GET ERR_EMPTY_RESPONSE

I have this Error when I'm trying to load my website
GET http://localhost:3000/ net::ERR_EMPTY_RESPONSE
I'm using Mean Stack Technologies,
When I remove app.use(bodyParser.json); from my code the page load very well
the code of my server.js file :
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var app = express();
var authenticationController = require('./server/controllers/authentication-controller');
mongoose.connect('mongodb://localhost:27017/time-waste');
app.use(bodyParser.json);
app.use('/app',express.static(__dirname + '/app'));
app.use('/node_modules',express.static(__dirname + '/node_modules'));
app.get('/',function(req,res){
res.sendfile('./index.html');
});
//Authentication
app.post('/api/user/signup',authenticationController.signup);
app.listen('3000',function(){
console.log("listening on port 3000");
});
the auth controller file
var mongoose = require('mongoose');
var User = require('../datasets/users');
module.exports.signup = function(req,res){
console.log(req.body);
var user = new User(req.body);
user.save();
res.json(req.body);
};
the angular controller
angular.module('TimeWaste').controller('signUpController',['$scope','$state','$http',function($scope,$state,$http){
$scope.createUser = function(){
console.log($scope.newUser);
$http.post('api/user/signup',$scope.newUser).success(function(response){
}).error(function(error){
console.log(error);
});
};
}]);

AngularJs Server Node js /get

Hello I have for this moment a fake backend with httpbackend in my angular Project. But I want to transfer my fake backend in a server node js but I don't know.
So For this moment I have this :
var express = require('express')
, path = require('path')
, fs = require('fs')
, bodyParser = require('body-parser')
, morgan = require('morgan');
var apps = express();
var staticRoot = __dirname + '/';
apps.set('port', (process.env.PORT || 3000));
apps.use(express.static(staticRoot));
apps.use(bodyParser.urlencoded({ extended: false }));
apps.use(bodyParser.json());
apps.use(morgan('dev'));
apps.use(function (req, res, next) {
var ext = path.extname(req.path);
if (ext !== '') {
return next();
}
});
apps.get('/getTpl', function (req, res) {
res.writeHead(200);
res.end(JSON.parse(["tp1", "tp2", "tp3", "tp4", "tp5", "tp6", "tp7"]));
});
apps.listen(apps.get('port'), function () {
console.log('serveur en route, port : ', apps.get('port'));
});
My controller :
ctrl.tpls = [];
ctrl.tplJson = undefined;
diapoService.getTpl().then(function (response) {
ctrl.tpls = JSON.stringify(response.data);
console.log(response.data);
});
function getTpl() {
return $http({
method: 'GET'
, url: '/getTpl'
});
I want to send my array in my select but my select is empty why ? please
Thank you so much for your answer
You have to change this function:
apps.get('/getTpl', function (req, res) {
res.status(200).json(["tp1", "tp2", "tp3", "tp4", "tp5", "tp6", "tp7"]);
});
Additionally I do not use Angular, but I don't think that you have to stringify the response:
diapoService.getTpl().then(function (response) {
ctrl.tpls = JSON.stringify(response.data); // <- Is this necessary?
console.log(response.data);
});

How to properly call an external api to use from within express application to build my own restful api?

I'am trying to create a restful api but I need to use an external api quandl to build my api, when i try to use my api from the client(built in angularjs) i get a 500 internal server error and No default engine was specified and no extension was provided in command line. i know my api work cause i tested it with postman, its just not working from the client.
I tried looking at this post : express js 4 how to serve json results without rendering any views /css but it wasnt helpful.
module.exports = function(io){
var q = require('q');
var request = require('request');
var mongoose = require('mongoose');
var Stock = mongoose.model('Stock');
var base_url = "https://www.quandl.com/api/v3/datasets/WIKI/";
var dotjson = ".json"
var apiKey = "?api_key=" + process.env.quandl_apiKey;
function sendJsonResponse(res,status,content){
res.status(status);
res.json(content);
}
// get stock data using quandl api
function stockData(name){
var deferred = q.defer();
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth() + 1;
var date = d.getDate();
request({
url: base_url + name + dotjson + apiKey,
qs:{
start_date:(year-1) + '-' + month + '-' + date,
end_date:year + '-' + month + '-' + date
}
},function(error,response,body){
if(error){
deferred.reject('Error: ' + error);
}else if(response.statusCode !== 200){
deferred.reject('Invalid Status Code: ' + response.statusCode);
}else{
deferred.resolve(body);
}
})
return deferred.promise;
}
// get stock data that is stored in database
function getStockInDatabase(req,res){
Stock.find({},function(err,stock){
if(err){
sendJsonResponse(res,404,err);
} else {
sendJsonResponse(res,200,stock);
}
})
}
// create stock data to be stored in database
function createStockData(req,res){
var stockDatas;
stockData(req.body.name.toUpperCase())
.then(function(stock){
stockDatas = JSON.parse(stock);
Stock.create({
name:stockDatas.dataset.name,
symbol:stockDatas.dataset.dataset_code
},function(err,stk){
if(err){
sendJsonResponse(res,400,err)
}else{
sendJsonResponse(res,201,stk);
io.emit('stock',stockDatas);
}
})
})
.catch(function(err){
sendJsonResponse(res,404,err);
})
}
// delete stock data in database
function deleteStockData(req,res){
Stock
.findByIdAndRemove(req.body._id)
.exec(function(err,stock){
if(err){
sendJsonResponse(res,404,err);
}else {
sendJsonResponse(res,204,null);
}
})
}
return {
getStockInDatabase:getStockInDatabase,
createStockData:createStockData,
deleteStockData:deleteStockData
}
}
angular service to use api:
(function(){
'use strict'
angular
.module('app.common')
.factory('stockService',stockService);
stockService.$inject = ['$http'];
function stockService($http){
function getStock(){
return $http.get('/api/stocks');
}
function getStockInDatabase(){
return $http.get('api/stocks/database');
}
function createStock(data){
return $http.post('/api/stocks',data);
}
function deleteStock(data){
return $http.delete('/api/stocks',data);
}
return{
getStockInDatabase:getStockInDatabase,
createStock:createStock,
deleteStock:deleteStock
}
}
})()
app.js configuration
require('dotenv').load();
var express = require('express');
var socketio = require('socket.io');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var io = socketio();
require('./api/models/db');
var app = express();
app.io = io;
var apiRoute = require('./api/routes/index')(io);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'client')));
app.use('/api', apiRoute);
app.use(function(req, res) {
res.sendFile(path.join(__dirname, 'client', 'index.html'));
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500).send({
message: err.message,
error: {}
})
});
module.exports = app;
No default engine specified error comes when you have not specified any content serving engine in express.. for you views or html files.
Try using
app.set('views', 'html page location');
app.set('view engine', 'jade');
You might have to additionally require jade.

Resources