I am trying to create a page to display all the forum posts...everything works fine, but I notice that after I create a post (when it redirects to show all of the posts) - in firebug, the post call hangs for a very long time. However, the data gets sent through, even though it looks like the post call is still pending...because it shows up on the page with all of the posts, that gets loaded right after. This is how I am doing it now.
post controller (post.js):
'use strict';
angular.module('appApp')
.controller('PostCtrl', function ($location, $scope, $http) {
$scope.errors = {};
$scope.post;
$scope.postit = function(form) {
$scope.submitted = true;
if(form.$valid) {
console.log($scope.post.posttitle + " this is $scope.post");
$http.post('/api/post', $scope.post).success(function() {console.log("no errors whoohoo")});
$location.path('/forum');
}
};
});
As you can see, right now, I am executing the redirect ($location.path) after the post call line. The redirect works fine like this...however - if I try to put the redirect in the success function:
$http.post('/api/post', $scope.post).success(function() {$location.path('/forum'); console.log("no errors whoohoo")});
the redirect never happens, and it just hangs on the post call. Does anyone know what is going on? I think the post call should only take a few ms to complete (it is just storing a post title, and content).
The post call hangs regardless of which way I do it...it's just the second way doesn't redirect the page.
UPDATE
As suggested in the comments, something is wrong with my server side code - I may have isolated the problem.
This is the function that gets called when I want to list all the posts on the page (api.js):
exports.posts = function(req, res) {
return Post.find(function (err, posts) {
if (!err) {
console.log(posts + " server side posts function route");
return res.json(posts);
} else {
return res.send(err);
}
});
};
The console.log message never appears, so this must be where it is getting hung up...any ideas?
The area of code that calls this function looks like this:
app.route('/api/post')
.get(api.posts);
It is one of my express routes.
It turns out that using $location.path('/xxx') wasn't enough, I needed to also use res.redirect on the express side for the redirect to actually work. (Had to use both).
Related
As the title says, i have a part of my react app that tries to get some data from my database, making a select based on the value I passed to it. So im gonna go ahead and first show the code where i think the problem lies:
So first, this is the function from one of my forms that sends the request to the server, i know code is probably ugly, but i can tell from the console.logs that the parameters im sending are what i intend to send(a string called "licenciaInput"
async handleClickLicencia (event) {
event.preventDefault();
console.log(this.state);
console.log("licenciaInput: "+this.state.licenciaInput);
const datoBuscar = this.state.licenciaInput;
axios.get('http://localhost:3001/atletas/:licencia',this.state)
.then(response =>{
console.log(response)
})
.catch(error =>{
console.log(error)
})
And then, i have this function which is called in that localhost route which attempts to get "licencia", and launch a select in my postgresql db where licencia="whatever", you can see the sentence in the code:
const getAtletasByLicencia = (request, response) => {
const licencia = request.body.licenciaInput;
console.log("Request: "+request);
console.log("what the server gets: "+licencia);
// const licencia = request.licenciaInput;
const sentencia ="SELECT * FROM atleta WHERE licencia ='"+licencia+"'";
pool.query(sentencia, (error, results) =>{
if(error){
throw error
}
response.status(200).json(results.rows)
})
}
As you can see, i have console.logs everywhere, and i still cannot access whatever element i send, because i always get on the server console "undefined" value.
TLDR:How can i access the "licenciaInput" i passed from my client form to my server, i have tried request.body.licenciaInput, request.params.licenciaInput, and request.licenciaInput, but none of those seem to work
I also know i have to treat after that the data i receive from the server, but i need to solve this before looking two steps ahead. Im also really new to React and node/express, so feel free to burn me with good practices im not meeting.Thanks in advance
EDIT: Im also adding this code that i have which shows the route for my method in the server:
app.get('/atletas/:licencia', db.getAtletasByLicencia)
As #Gillespie59 suggested that i should send a POST request, but i dont think i should if im both trying to send a parameter to the server to make a select, and then send the results back to the client
Change your request to:
axios.get(`http://localhost:3001/atletas/${this.state.licenciaInput}`)
...
and your route (if you are using express) should look like this:
app.get('/atletas/:licencia', function (req, res) {
var licencia = req.params.licencia
...
})
As you are using request.body you should send a POST request with axios and add a body.
Thanks for looking into my question.
I have a node/express server, configured with a server.js file, which calls urls.js which in turn calls controllers for handling http requests, and all of them are configured identically and all work fine, except for one.
It's my OrderController. The OrderController.js never gets called, and thus never returns any HTTP responses even though I'm as sure as I can be that it should be getting called.
I've tried adding logging statements all over OrderController.js, but they never fire. Nothing in my OrderController.js is running at all.
I've inspected my urls.js file carefully but can find no clue why OrderController would fail to load, while my other 8 controllers all work fine.
I've added logging statements to my server.js file to ensure that my server.js file is indeed handling all http requests and passing them correctly to my urls.js file.
I've added logging statements to my urls.js file to confirm that it is being executed.
I've logged the controllers, both require(OrderController.js) and my other controllers, and inspected the dumped json objects, but couldn't determine anything different or mistaken from the output I got.
The repository is: https://github.com/allenchan3/foodproject/tree/40a43231ae49989a35fb0c004a897bbee69fe669
In theory, the problem should be somewhere in urls.js:
const path = require("path");
const staticFilesError = require("./errors").errorHTML;
module.exports = function(app, staticDir) {
const loginRegController = require(path.join("..","controllers","LoginRegController"));
const controllers = {
'categories': require(path.join("..","controllers","CategoryController")),
'diningrooms':require(path.join("..","controllers","DiningRoomController")),
'ingredients':require(path.join("..","controllers","IngredientController")),
'items': require(path.join("..","controllers","ItemController")),
'options': require(path.join("..","controllers","OptionController")),
'orders': require(path.join("..","controllers","OrderController")),
'tables': require(path.join("..","controllers","TableController")),
'users': require(path.join("..","controllers","UserController")),
};
for (key in controllers) {
app.use("/api/"+key, controllers[key]);
}
app.use(loginRegController);
app.get(/^\/api\//, (req, res) => res.status(404).json({"error":req.url+" not found"}));
app.get("*", (_,res) => res.sendFile(staticDir+"/index.html"));
}
I am just trying to make HTTP GET requests to /api/orders/ and get something from the order controller (currently it should get a list of all orders from my database). I also made a handler for /hello so /api/orders/hello should be at least returning something. Whats actually happening is no http response ever comes, not even a 404, and I don't have any idea why.
I cloned your repo and was able to reproduce the bug.
What is seems to be is that in authentication.js, the handleOrders() function only handles a user being a manager, bartender, server or cashier. If the req.session.userType is not set or it its equal to cook or customer, it is not handled by the if statement and will hang indefinitely.
Can you attempt to call the API as a user with a different type and confirm this?
You may need to an else as below to throw a 403 if the user is the wrong type.
function handleOrders(req, res, next) {
console.log('handling')
if (req.session.userType == "manager") {
console.log('i am manager')
next();
} else if (["bartender","server","cashier"].indexOf(req.session.userType) > -1) {
console.log('am i a cahsier or server or bartender')
if (req.url == "/api/order" && req.method == "GET") {
console.log('in this if')
next();
}
else {
//not a get
Order.findById(req.params.id,(err,data)=>{
if (err) {
console.log(err);
res.status(500).json(err);
} else {
console.log(data);
next();
}
});
}
} else res.status(403).send(errors.forbidden);
}
Basically what I wantto achieve is a searchable/filterable listview
so far I'm able to fetch some data from a database and have express with pug render me a page showing the results in a listview.
Now I want to add the functionality of filtering the displayed listview.
Therefore on every keyup event within a textbox I make an AJAX post request to the server sending the query string from the textbox. So far everything works just fine, but when i try to "re-render" the page with the filtered resultset nothing happens in the browser.
My routes look like this:
var rechnungen;
router.get('/', function(req, res) {
connection.query('SELECT * FROM rechnungen ', function(err, result) {
rechnugen = result;
res.render('rechnungen', {rechnungen: result});
});
router.post('/:query', function(req, res) {
console.log("received ajax request");
console.log("with query " + req.params.query);
res.render('rechnungen', {rechnungen: {}});
});
initially the query statement fetches the data and res.render works just fine, when I make the AJAX call everything seems to work as well (the console log output matches my input) but regardless what i try to pass to the view (res.render) in the post route nothing happens.
Is it not possible to "re-render" a view or is there any other conceptional misstake I make?
thanks for your help
AJAX POST call is not a traditional HTTP call.
The rendered page sent from the server will come in the response object of success handler of your AJAX call.
So, either
replace whole HTML with the response HTML, or
make a traditional HTTP form POST, in that case the browser by-default renders the response of the server.
I am using the route to check if a token is valid or not. If it isn't I route the user to the log in page. I want to let the users know they're being logged out either as an alert or on the page.
What happens is a user clicks on Link A (to take them to another page on the website), the route calls a validate.js file:
route.js
var checkToken = require('../validate.js');
router.use(checkToken.checkToken);
This then calls the validate.js file which makes a HTTP call to check
if the token is valid, if it isn't it redirects the user to the Login
page:
validate.js
var checkToken = function(req, res, next) {
if (config.enableTokenValidation) {
var usersToken = req.user.token;
validateToken(receivedToken, req.requestId, function(err, response, body) {
if (err || response.statusCode != 200) {
console.log("Error, token is not valid");
res.redirect("/auth/logout/");
} else {
return next();
}
});
How can I send a message to the loginView.js file so that I can display the error in the front end (or create an alert)?
But as this happens in the middleware and it is other routes to other pages within the program that trigger the validation check, the login page doesn't make the check and therefore I can't get the response there to alert the user.
If there any way of achieving this using the way I'm going about it, or are there any other ways I can go about it?
Many Thanks
Instead of doing
res.redirect();
Why do not you send an error message like
res.status('401').send({error:'Invalid Token'});
Then you can take the necessary steps in the errorHandler() of the api call.
You can return an object that contains a method that fires an Alert message (or a change in your HTML, if you want to change the view). Then you use yourObject.method from the Frontend.
I send JSON POST data via a form in a MEAN environment to my server. On the server side, I process the data inside of a waterfall function, using the async library, including various operations such as:
[...]
- create a database entry for a new author
- create a database entry for a new book
- associate the new book to an author (reference to book ID)
[...]
This is the method called by my route, which handles the associated POST-request:
exports.createAuthor = function(req, res) {
console.log(req.url+' !!!POST REQUEST INCOMING!!! '+req.body);
async.waterfall([
function(callback){
//create Author db entry
},
function(parameter, callback){
//add author to additional directory (db action)
},
function(parameter, callback){
//create book db entry
},
function(parameter, callback){
//associate book to author (db action)
}
], function (err, result) {
console.log('DONE!!!');
res.send('200');
});
}
This is the client-side AngularJS controller code:
searchApp = angular.module("searchApp",[]);
searchApp.controller('authorCreator', function ($scope,$http) {
$scope.tags = [];
$scope.sendAuthor = function(){
alert('I was called!');
$http({
method: 'POST',
url: '/newauthor/',
data: { 'authorname' : $scope.authorName,
'authordescription' : $scope.authorDescr,
'bookname' : $scope.bookName,
'tags' : $scope.tags }
})
.success(function(data){
//no actions yet
})
.error(function(){
//no actions yet
});
};
});
This is the AngularJS form:
<div ng-controller="authorCreator">
<form>
<p>Author name: <input ng-model="authorName"></p>
<p>Author description: <input ng-model="authorDescr"></p>
<p>Book name: <input ng-model="bookName"></p>
<p>Tags:<input ng-model="tags"></p>
<p><button ng-click="sendAuthor()">Send</button></p>
</form>
</div>
I noticed that, if the waterfall-process is "stuck" somewhere, meaning the client does not get an answer to it's request whatsoever, the POST request seems to be sent a second time automatically (as soon as the browser is giving a timeout according to firebug). According to firebug, a second POST request does not seem to be sent by the browser, so the call must be initiated from somewhere else.
I found out by checking the database (multiple documents with identical values, except the ObjectID of course) and monitoring the node.js console window where I output incoming POST data. Again: as soon as the entire waterfall-process completes, hence the client browser does not abort the post request after a while, and res.send('200') executes, the error does not occur (= no multiple db entries).
Can anyone please tell me, who does initiate this second POST request and how may I deactivate it?
Cheers
Igor
Try adding this:
exports.createAuthor = function(req, res) {
if(req.method == 'POST' && req.url = 'REQUESTEDURL'){
console.log('POST REQUEST INCOMING!!! '+req.body);
async.waterfall([
//TODO...
]);
}
Maybe the problem is that the favicon or some other resource is doing a request to
After spending some time on that issue I found out, that this error seems to be based on missing answers to the client (be it via res.json, res.sendfile, ...). Therefore the client seems to re-send the request after some time, thus executing server-side code a second time. Responding to the client in reasonable time solves this issue. Sorry for the confusion.
i "fixed" this by adding
.get('/favicon.ico:1', (req, res) =>{
//do nothing because i dont care
})