1

Hello i create a simple nodejs+express+mysql+angular+yoeman application.

On that application i do the following:
1. I create express application and run the server on port:3000
2. I have created a simple rest api the gets products from mysql(i have complicated tables) db.
This is the productsController.js that gets the rows from productsModel.js

var productModel = require('../models/productsModel');

var products = {};

/*controller that handles Products CRUD*/
products.list = function(req, res){
  console.log('REQUEST TO GET PRODUCTS (productsController)')
  var prod = productModel.list();
  prod.then(function(products){
    res.send(products);
  }, function(){
    res.send({status:'error',error:'Error occured while fetching data from database.'});
  });
}

module.exports = products;

3. For client side i run gulp serve and opens the angular application on localhost:4000/#/

4. Inside index.config.js if set the base url for the rest api server : function config($logProvider, toastrConfig, RestangularProvider) {

RestangularProvider.setBaseUrl('http://localhost:3000');

5. Inside the main controller i call restangular to get the data, like this:

  function MainController($timeout, $scope, $http, $log, Restangular) {
    var vm = this;

    vm.awesomeThings = [];
    vm.classAnimation = '';
    vm.creationDate = 1480625671827;

    Restangular.all("products").getList().then(function() {
      console.log("All ok");
    }, function(response) {
      console.log("Error with status code", response.status);
    });

6. Two screenshots that are 2000 words(the node server and the client errors).

node server gets data from mysql , correctly

The errors that i get on the client

Am i missing something ? Any help would be appreciated.

Update question(show my app.js) when i use the headers i still get the error

var express = require('express');
var cors    = require('cors');/*add cors module to support CORS*/
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var         _  =  require('lodash');
var routes     =  require('./routes/routes');

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
/*app.use(cors());*/
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: false }));

// parse application/json.
app.use(bodyParser.json());
app.use(function(req, res, next) {
   res.header("Access-Control-Allow-Origin", "*");
   res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
   next();
 });


app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'app')));/*έκανα το folder 'public' -> 'app' */

app.use('/', index);
app.use('/users', users);

/*Load the routes*/
routes(app); /*here i have my /products route*/

// 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 handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
Community
  • 1
  • 1
Theo Itzaris
  • 4,321
  • 3
  • 37
  • 68
  • 3
    You are a cors victim .. try using npm cors module and in ur app.js put app.use(cors()) assuming for development . in production allow only secure domain for cors – Samundra Khatri Dec 06 '16 at 18:31
  • This post may help: http://stackoverflow.com/questions/12630231/how-do-cors-and-access-control-allow-headers-work – leo.fcx Dec 06 '16 at 18:33
  • 1
    add this on your app.js on the node project! // CORS, not for production use :) app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE'); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); after the app.set('view engine', 'jade'); if you are using the express generator – rule Dec 06 '16 at 18:33
  • You need to add CORS headers with the server that serves your main HTML document. – bhantol Dec 06 '16 at 18:43
  • That is why it is the best community here, we share our knowledges without know each other. Thank you Samundra KC i am a cors victim indeed and by adding the app.use(cors()); , i now get the data on the client. But I also added rule's sollution although i used to have it , and i still get the error. Maybe it is the order inside my app.js ? I update my answer with the app.js file. Thanks to all. – Theo Itzaris Dec 06 '16 at 18:50

0 Answers0