Angularjs Ajax Post to Epressjs - javascript

I am trying to make a Ajax request from Angularjs to Express js. Below code is my angularjs and express js route.
The problem is I am getting 500 Server error when I make a POST and get seems to work without any problem
AngularJs code
$http.post('http://www.mydomin.com/abc',str)
.success(function(data) {
alert(data);
})
.error(function(data) {
alert(1);
});
Here str can be just a letter or anything str= 't'; for example
ExpressJs route
module.exports = function(app) {
app.post('/abc', function(req, res) {
console.log('ggg');
});
};
This route is added to app.js as well
require('./routes/test')(app);

Try changing your code to something like this:
$http.post('/abc',{name: str})
.success(function(data) {
alert(data);
})
.error(function(data) {
alert(1);
});

app.js
var express = require('express');
var app = express.createServer();
app.configure(function(){
app.use(express.json());
app.use(express.urlencoded());
});
require('./routes/test')(app);
app.listen(3000);
routes/test.js
module.exports = function(app){
app.post('/abc', function(req, res){
console.log(req.body);
res.send("ok");
});
}
This is a really basic app that should work without issue. Not sure where you are differing, but this is a bsic template to go off of.

Related

NodeJS URL Routing and Render HTML

Im new at nodejs programming and im having a little problem now. When i try to go localhost:3000/ i want to go homeController and index function prints the HTML file.
APP.JS
const express = require('express')
const mongoose = require('mongoose')
const mongodb = require('mongodb')
const app = express();
const homeController = require('./home/homeController.js');
app.get('/', function(req, res) {
res.redirect(homeController.index);
});
app.listen(3000, () => console.log('Example app listening on port 80!'))
HOMECONTROLLER.JS
var path = require("path");
exports.index = function(req, res){
res.sendFile(path.join(__dirname+'/index.html'));
};
console.log('test33');
Also i am using exports to seperate app.js from other controllers. Is this the right way? I have a history with Python Django framework and we used to use URLs to navigate our program.
Thanks.
OUTPUT
Cannot GET
/function%20(req,%20res)%7B%0A%20%20res.sendFile(path.join(__dirname+'/index.html'));%0A%7D
Your problem is that homeController.index is a function, but you're not calling it. Replace:
app.get('/', function(req, res) {
res.redirect(homeController.index);
});
with:
app.get('/', homeController.index);
Your homeController.js exports an index function which requires two parameters reqand res.
So you have to update your app.js accordingly :
app.get('/', function(req, res) {
homeController.index(req, res);
});
edit: by the way, your app is listening to port 3000

Express.js Handle unmached routes

Fellows I develop a Rest API and I want when a route does not exist to send a custom message instead of an html one that express.js sends by default. As fas as I searched I could not find a way to do that.
I tried to do:
app.all("*",function(req,res){
res.status(404)
res.header("Content Type","application/json")
res.end(JSON.stringify({message:"Route not found"}))
});
But it matches and all already implemented methods. I want only the unmached one to get handled by my app.
Edit 1
For each enndpoint I create a seperate file having the following content: eg. myendpoint.js
module.exports=function(express){
var endpoint="/endpoint"
express.get(endpoint,function(req,res){
res.end("Getting data other message")
}).post(endpoint.function(req,res){
res.end("Getting data other message")
}).all(endpoint,function(req,res){
res.status(501)
res.end("You cannot "+res.method+" to "+endpoint)
})
}
An in my main file I use:
var endpoint=require('myendpoint.js')
var MyEndpointController=endpoint(app)
app.all("*",function(req,res){
res.status(404)
res.header("Content Type","application/json")
res.end(JSON.stringify({message:"Route not found"}))
});
1.Declare all of your routes
2.Define unmatched route request to error respose AT the END.
This you have to set it in the app. (app.use) not in the routes.
Server.js
//Import require modules
var express = require('express');
var bodyParser = require('body-parser');
// define our app using express
var app = express();
// this will help us to read POST data.
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8081;
// instance of express Router
var router = express.Router();
// default route to make sure , it works.
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
// test route to make sure , it works.
router.get('/test', function(req, res) {
res.json({ message: 'Testing!' });
});
// all our routes will be prefixed with /api
app.use('/api', router);
// this is default in case of unmatched routes
app.use(function(req, res) {
// Invalid request
res.json({
error: {
'name':'Error',
'status':404,
'message':'Invalid Request',
'statusCode':404,
'stack':'http://localhost:8081/'
},
message: 'Testing!'
});
});
// state the server
app.listen(port);
console.log('Server listening on port ' + port);
Please note : I have prefix '/api' in my routes.
Please try http://localhost:8081/api
You will see '{"message":"hooray! welcome to our api!"}'
When you try http://localhost:8081/api4545 - which is not a valid route
You would see the error message.
First you need to define all existing routes then at last you have to define no
route. order is very important
// Defining main template navigations(sample routes)
app.use('/',express.static(__dirname + "/views/index.html"));
app.use('/app',express.static(__dirname + "/views/app.html"));
app.use('/api',express.static(__dirname + "/views/api.html"));
app.use('/uploads',express.static(path.join(__dirname, 'static/uploads')));
//If no route is matched by now, it must be a 404
app.use(function(req, res, next) {
res.status(404);
res.json({status:404,title:"Not Found",msg:"Route not found"});
next();
});
Can't post as comment (reputation is too low ...) but did you define this route after all your other paths ?
The order is really important, you should first define all your routes and then have this one.
on my case for the safetyness of my routes life cycle I used this **/** or */*, *(asterisk) operator stands for all, and here's my example.
app.use('**/**',express.static(path.join(__dirname, './public/not-found/index.html')));

Trouble with express routing

Hello I am fairly new to node, I having trouble with routing in an express app. I have looked at documentation and searched for answers, tried a little bebugging but no luck.
here is current code on github https://github.com/Ongomobile/my-api
I am using express router to route from 2 files in my routes directory, the index route works fine
but the end points in routes/products.js do not work with app.use(), they do work if I use app.get() or if I put end points in routes/index.js
In my server.js file (I believe my problem is in code below)
var indexRoutes = require('./routes/index'),
productRoute = require(‘./routes/products’)
app.use('/', indexRoutes);
app.use('/product', productRoute);
Routes/products.js
var express = require('express');
var router = express.Router();
var Product = require('../model/product');
router.get('/product', function(req, res) {
Product.find({}, function(err, products) {
if(err) {
res.status(500).send({error: "Products not found..."});
}else {
// res.send(products);
res.send("<h1>Products will show here when populated</h1>");
}
});
});
router.post('/product', function(request, response) {
…….
});
module.exports = router;
found what my problem was in products.js end points I just changed to router.get('/') instead of router.get('/product') – Mike Haslam just now edit

jQuery Not Working in Express JS - NodeJS

Ok, so I'm new to Express. I'm messing around with sessions and ajax calls, but the problem I'm having is that whenever I run my app, my jquery doesn't work for some reason. This is the code I have:
app.js
var express = require("express");
var mongoose = require("mongoose");
var bodyParser = require("body-parser");
var session = require('express-session')
var app = express();
app.use(express.static("public")); // I understand this is the directory where I would need to put all my static files: css, js, images, etc.
app.set("view engine", "jade");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
//Set secre pass for the session
app.use(session({secret:'password'}));
app.get("/",function(req, res){
if(req.session.userName){
res.render("admin", {session_name: req.session.userName});
}else{
res.render("home");
}
});
app.post("/example-ajax", function(req, res){
res.send(req.body.email); // return the email that was sent by the client
});
app.post("/log-in", function(req, res){
req.session.userName = req.body.name;
res.redirect("/");
});
app.get("/log-out", function(req, res){
req.session.destroy();
res.redirect("/");
});
app.listen(8080);
admin.jade
extends layout_head.jade
block content
div(class="container")
div(class="row")
div(class="col-lg-6 col-lg-offset-3")
h1 Logged In!!
h3 Logged in as: #[b #{session_name}]
a(href="/log-out") Log Out
br
div(class="btn btn-info testAjax") Test Ajax
script(src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js")
script(href="/css/bootstrap/js/bootstrap.min.js")
script(href="/js/main.js")
main.js
$(document).ready(function(){
alert("Loaded");
$(".testAjax").on("click", function(){
alert("test");
$.ajax({
type: 'POST',
url: '/example-ajax',
data: {
email: "admin#yahoo.com"
},
success: function(data){
// data = the email being returned from the server
console.log("Your email is: " + data);
}
});
});
});
So like I said, the jquery doesn't run whenever my page loads up or when I click the testAjax button. When I check the console, it doesn't give me any errors so I don't know what is causing the problem.
My second question is: Is this the right way to make ajax calls in Express?
Any help is greatly appreciated. Thanks.
I just needed to change href to src in the script tags.

Express.js - Single routes file that manages all the routes

I am kinda new to express.js and did not find a matching answer to my problem yet.
I've got an express app with a folder structure like this:
app/
|--app.js
|--routes/
|--|--index.js
|--|--news.js
|--|--users.js
|--some_other_folders/
As for now, I've got my routes managed in the app.js, like this:
var index = require('./routes/index');
var users = require('./routes/users');
...
app.use('/', index);
app.use('/users', users);
...
This works fine, but I originally wanted to manage all my routes with only one file, so that I only need to reference this file in the app.js.
Something like this:
[app.js]
var routes = require('./routes/routes');
app.use('/', routes);
[routes/routes.js]
...
router.get('/', function(req, res) {
res.render('index.html');
});
require('./users'); // This is meant to refer to the users routes
...
Is there a way to include my other route files (like users, news, ...) into the "main"-route file?
Or are there maybe other best-practices to mange routes within express.js?
Thank you so much for your help!
Yes, there are good way to do this
[app.js]
var routes = require('./routes/routes')(app);
[routes/routes.js]
var user = require('./user'); // get user controllers
module.exports = function(app) {
app.get('/', function() { ... });
app.get('/another-path', function() { ... });
app.get('/user/:id', user.display);
app.post('/user/:id', user.update);
};
[routes/user.js]
module.exports.display = function(req, res) {
...
res.render('user', data);
}
module.exports.update = function(req, res) {
...
res.render('user', data);
}

Categories