Cannot GET / while using a grammar Api - javascript

I am trying to use API to check the grammar of the sentence. but when I don't know it is giving me the error Cannot GET / please tell me where I am wrong.
const express = require('express');
const https = require('https');
const app = express();
app.get('/', function(req, res){
res.sendFile(__dirname + "/index.html");
});
app.post("/", function(req, res){
const text = req.body.cityName;
const url = "https://www.stands4.com/services/v2/grammar.php?uid=8816&tokenid=u9K3iEcIcjmS84B6&text=" + text + "&format=json";
https.get(url,function(response){
response.on("data", function(data){
const grammar = JSON.parse(data);
const fault = grammar.matches.message;
console.log(fault);
res.write("<p>The problem in text :" + fault + "</p>");
res.send();
});
});
});
app.listen(port = 3000, function(){
console.log("Server is running on port 3000 ");
})

Are you trying to access localhost:3000 via the browser? if so you're using app.post change it to app.get

This error usually occurs when target an invalid endpoint, make sure that you use correct url and correct method

Your controller is a POST controller thus the error. You either do a post call or you change to the controller to GET.
app.get("/", function(req, res) ...

If you are trying to hit your own API, then the problem is that your controller is being a POST controller. That is why it throws you Cannot GET.
You can change app.post to app.get or, you can try calling POST method instead of GET.

Related

storing express "res" variable and using it later?

I have a simple nodeJs server with express and I have an external module that handles sending the response to the requests. In order for this file to work, it needs to access express res variable. Before, I used to send this variable to the module functions to use it, but then I tried to use a middleware to store this variable in the module and not send it every time I'm calling a function, and it worked!
This is the code:
// app.js
var http = require('http');
var express = require('express');
var app = express();
var response = require('./response.js');
// store the value of 'res' in the response module
app.use(function(req, res, next) {
response.setRes(res);
next();
});
app.get("/", function(req, res){
response.success("Welcome"); // works fine
});
app.get("/images", function(req, res){
response.forbidded("Forbidded"); // works fine
});
var server = http.createServer(app);
server.listen(3000, function(){
console.log("listening... ");
});
and this is the other module
// response.js
exports.setRes = function(_res){
res = _res;
};
exports.success = function(msg){
res.status(200).send(msg);
};
exports.forbidded = function(msg){
res.status(403).send(msg);
};
My question is: Is this a good approach? and will this affect my application if the number of users increases (I'm worried that one user might get the res of another user)

Simple redirect in Express with static file

I am new to Node and Express.
I've got a static html page where the users posts his username via ajax to my server. Then I want to redirect him to another html file.
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(__dirname + "/public/arena.html"));
app.get('/',function(req,res){
res.sendFile(__dirname + "/public/index.html");
});
app.post('/login',function(req,res){
var username=req.body.username;
console.log("User name = "+username);
res.redirect(__dirname + "/public/arena.html");
});
var server = app.listen(3000);
I get the username and also the respond in the browser but the server does not redirect me to arena.html. I also don't get any errors.
Why are these "easy" things so difficult in Node?
Thank you guys so much for your help.
The problem in this case is that it looks like you had some test (debugging?) code inserted into your POST route that is stopping the redirect call from running.
Here's the modified (corrected) version of your program, which will redirect the user in the way you want:
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(__dirname + "/public/arena.html"));
app.get('/', function(req, res) {
res.sendFile(__dirname + "/public/index.html");
});
app.get('/arena', function(req, res) {
res.sendFile(__dirname + "/public/arena.html");
});
app.post('/login', function(req, res) {
var username = req.body.username;
console.log("User name = " + username);
// Note how I'm redirecting the user to the /arena URL.
// When you issue a redirect, you MUST redirect the user
// to a webpage on your site. You can't redirect them to
// a file you have on your disk.
res.redirect("/arena");
});
app.listen(3000);
I had to do a couple of things to get this working:
Get rid of your call to res.end. Whenever you call res.end, it will END the request, so any code that happens AFTER that call in the route will not run.
I had to create a new route for /arena. This just renders the arena.html file that you've created. This is required if you want to 'redirect' the user to an arena page.
I had to update your redirect code to actually redirect the user to /arena (the new route I created in step 2), so that the user will then hit your /arena route, and finally get back the template you are trying to show them.
Your res.redirect function is never executed because you are returning from function right before that statement.
You pass a URL to res.redirect(). That URL should be a URL that you have an appropriate route for that will serve the desired file.
Instead you are doing:
res.redirect(__dirname + "/public/arena.html");
But, that isn't a URL at all. That's a path name on your local hard disk. res.redirect() sends a URL back to the browser and, if the browser is following redirects, it will then request that URL from scratch as a branch new request. So, you need to send a URL (not a path) and you need to send a URL that you have a route configured for that will serve the desired file.
It also looks like your express.static() statements might be incorrect. For us to help more specifically with those, we need to know where the static HTML files are on your hard drive relative to __dirname and we need to know exactly how you want the URLs for them to work. For example, do you want a request for /arena.html to serve __dirname + /public/arena.html? Is that what you are trying to do? Please explain that part so we can advise more specifically on your express.static() statements.
If that is the case, then you can change your redirect to:
res.redirect("/arena.html");

Undefined variable Express Js - Node JS

I want to build an API with node js.
i post the data using postman.
I don't know why, every time I post the data, I got nothing.
Here is my code :
let router = require('express').Router();
let bodyParser = require('body-parser');
let db = require('./queries');
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: false }));
router.post('/test', function (req, res) {
res.send('post data ' + req.body.clinic_name)
});
req.body.clinic_name has no value, thats why it will undefined data.
i try clinic_name, address, phone, and fax. all of them returning undefined data.
please help me to fix this issue.
thank you.
use the "application/x-www-form-urlencoded" tab in POSTMAN or you can make sure your client has header '"Content-Type: "application/json"', and send a raw json
Problem is that you have sent the data res.send('welcome, ' + req.body.clinic_name) first and then printing in console.log(req.body);
It should be like
console.log(req.body);
res.send('welcome, ' + req.body.clinic_name)

Cookies not getting set in node.js

Im trying to set cookies for my website using node.js and express.js. Heres a simplified version of my code:
var express = require('express');
var cookieParser = require('cookie-parser');
var app = express();
app.use(cookieParser());
app.post('/testCookies', function(req, res) {
console.log(req.cookies); //empty object
res.cookie('username', 'test');
console.log(req.cookies); //still an empty object
res.end();
});
I tried POSTing twice in case the cookies somehow get set after the request (im not very familiar with cookies yet) but it doesn't change anything. The console does not show any errors.
You could use req.session() instead. That would let you do
req.session.username = "test";
See the docs here.

retain query string after Stormpath authentication and authorization in node express site

I have a node express app , using express-stormpath for authentication/authorization
I have a GET route which is called with certain jquery parameters.
If the user is logged in everything is working as expected.
If not the user login screen is shown.
After stormpath authentication and authorization is done my query params are lost.
Is there any way to retain those?
app.get('/myRoute', stormpath.groupsRequired(['admin']), function(req, res){
console.log('req.query ',req.query);
//do somehting with the query data
res.sendStatus(200);
});
after authentication req.query is {}.
Any ideas?
Thank you for the question, I work at Stormpath and I'm more than happy to help. Our express-stormpath library is open source, and we're always happy to fix bugs and review pull requests.
Can you tell me which version of our library you are using? At the moment I'm not able to reproduce the problem you are seeing. Here is a quick example that I put together with the latest version, 3.0.1:
'use strict';
var express = require('express');
var stormpath = require('express-stormpath');
var app = express();
var port = process.env.PORT || 3000;
app.use(stormpath.init(app));
app.get('/admins', stormpath.groupsRequired(['admins']), function(req, res){
res.json(req.query);
});
app.on('stormpath.ready',function () {
console.log('Stormpath Ready');
});
app.listen(port, function () {
console.log('Server listening on http://localhost:' + port);
});
With this example, I do the following:
1.) Assert that I'm not logged in, by deleting all my cookies for localhost.
2.) Type /admin?foo=bar into the URL bar.
3.) I am redirected to the login page.
4.) I login with valid credentials.
5.) I am redirected to /admins?foo=bar, as expected, and I see the req.query object in the body of the page that is rendered. This is only true if the user is in the admins group, if they are not I will see the "Unauthorized" error message page.
Can you compare my steps and my example to your application, and let us know if there are any differences? Thanks!
I don't think that stormpath is removing query from request.
But we can check it by adding middlewhare before stormpath initialization:
var express = require('express');
var stormpath = require('express-stormpath');
var app = express();
// binding middleware to assign req.query to req.q param
app.use(function(req, res, next) {
req.QUERY = req.query;
next();
});
function restoreQuery(req, res, next) {
req.query = req.QUERY;
next();
}
app.use(stormpath.init(app, {
// Optional configuration options.
}));
app.get('/myRoute',
stormpath.groupsRequired(['admin']),
restoreQuery,
function(req, res){
console.log('req.query ',req.query);
//do somehting with the query data
res.sendStatus(200);
});

Categories