App.js GET url parameter and send to routes/index.js - javascript

Here is my url: http://localhost:3000/?url=test
I'm running a Express so in my app.js I'm trying to get a the url parameter "test" send it to my routes/index.js
I'm sending a static variable no problem by using:
code in app.js
app.locals.url = 'a test string';
and receiving in my routes/index.js
var url;
url = req.app.locals.url;
Any idea how in app.js I can have:
app.locals.url = {the parameter "test" in the http://localhost:3000/?url=test}
Thanks!

You are trying to refer the query parameters in a false parameter.
While using Express.js, we refer to the parameters sent with GET request in the following manner -
var url = req.query.url; //url is the parameter sent - localhost:3000/?url=www.google.com

With express, you can use req.query
req.query.url
// => "test"
A representation of the HTTP request is passed to the callback function of most methods. This object will have property query, which will contain a property for each query string in the HTTP request.
app.get('/', function(req, res) {
url = req.query.url; // For http://localhost:3000/?url=test, val => 'test'
});

Related

Request to API based on URL/

I'm attempting to make a request to an API to get a users' avatar. This is the code I have, however it's returning a "player is not defined" error.
app.get(`/api/avatar/${player}`, function(req, res) {
res.redirect(`http://cdn.simulping.com/v1/users/${player}/avatar`);
});
Essentially, if the URL is /api/avatar/3925 it would send them to http://cdn.simulping.com/v1/users/3925/avatar.
Assuming you're using Express.JS for the routing, the correct way for doing that is:
app.get('/api/avatar/:id', function(req, res) {
res.redirect(`http://cdn.simulping.com/v1/users/${req.params.id}/avatar`);
})
Assuming you are using Express routing, then you would need to utilise route parameters.
The Express documentation provides:
Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in the req.params object, with the name of the route parameter specified in the path as their respective keys.
In this case:
Route path: /api/avatar/:player
Request URL: http://localhost:3000/api/avatar/3925
req.params: { "player": "3925" }
The working code:
app.get('/api/avatar/:player', function(req, res) {
res.redirect(`http://cdn.simulping.com/v1/users/${req.params.player}/avatar`);
});
You can read more about it in the Route Parameters section of the Express Routing Guide.

AJAX and Node JS/Express post not sending or receiving data

I am new to Node and I am trying to use app.post, everything works fine including the console log whenever the action is executed but it does not receive the data sent by the AJAX from main.js.
Here is a snipper of main.js which sends it:
$.ajax({
type: 'POST',
data: '{"title":'+ this.messageInput.value +'}',
url: 'http://localhost:3000/send'
});
Here is my config.js which should be receiving the data:
app.post('/send', function(req, res) {
console.log(req.body);
console.log('Send button clicked');
});
I am using bodyParser with express. So that is why I am using req.body. When I console log req.body I get undefined. When I console log req, I get a list of data but not what I sent.
I hope someone can help!
It's good that you are using body-parser, but have you defined a JSON parser in your app?
You didn't paste all of your code so add this if you don't already have it:
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// create application/json parser --> This is probably what you are missing
var jsonParser = bodyParser.json()
// POST /api/users gets JSON bodies --> Note how we use a jsonParser in our app.post call
app.post('/send', jsonParser, function (req, res) {
console.log(req.body);
console.log('Send button clicked');
})
Also, instead of constructing your data manually, just create an object and send it (remember JSON is short for - Java Script Object Notation)
var myData = {};
myData.title = this.MessageInput.value;
Then in your Ajax code, just use myData:
$.ajax({
type: 'POST',
data: myData,
url: 'http://localhost:3000/send'
});
Note: most of this example is taken straight from the body-parser Github Page, it has plenty of well documented examples so if you're not sure how to use the module, check it out

Node js router 404 with params

I wanna pass parameter to page. But have 404. My code:
app.js
var routes = require('./routes/index');
var app = express();
routes/index.js:
var express = require('express');
var router = express.Router();
router.get('/profile/:id', function (req, res) {
var id = req.params.id;
console.log(id);
res.render('profile', {id: id});
});
and i try http://localhost:3000/profile?id=56e2c3c2cdde3f64302ac154 but have Error: Not Found
Your route should be looks like:
http://localhost:3000/profile/56e2c3c2cdde3f64302ac154
It is automaticaly set req.params.id.
There is a difference between Path param and Query param . The Url you have defined
/profile/:id
Says to the routing framework that , I expect id as Path param i.e part of the resource path . But in the url request you made
http://localhost:3000/profile?id=56e2c3c2cdde3f64302ac154
You are sending id as query param . So the routing framework is unaware of the url with id as a query param . Hence it returns a 404 meaning "the server could not find what was requested" .

Angular $remove() and express delete()

How can I processed http DELETE request with express.js, created by angular-service's default $remove() method?
I have working post method:
On client (specifically inside angular controller):
$scope.obj.$save();
On server:
myRouter.post('/', function(req, res) {
var param = req.body.some_parameter; // got it fine
});
But it doesn't work with delete :)
On client:
obj.$remove();
On server:
myRouter.delete('/', function(req, res) {
//this route will be called, but I want get obj parametr like in post method
//can I do that? Or I shoud use request with parameter instead (?param=val)
//here I get undefined
var param = req.body.some_parameter;
});

How to iterate over body of POST request in Express.js?

I'm constructing a generic route handler for POST requests in NodeJS.
I need to iterate over the req.params of the POST request, without knowing beforehand what the parameters are.
I have tried the following without success:
console.log("checking param keys...")
Object.keys(req.param).forEach(function(key){
console.log(key +"is " + req.params(key) )
})
When I run this code, only the "Checking param keys..." gets printed.
Anybody knows how to do this?
I guess you're asking how to iterate form post from a url encoded POST request body, so it is bodyParser() middleware that did your trick.
req.params is an array that contains properties mapped by routing defined express app. see details from req.params, not the request body. Take the follow code for example:
var app = require("express")();
app.use(express.bodyParser());
app.post("/form/:name", function(req, res) {
console.log(req.params);
console.log(req.body);
console.log(req.query);
res.send("ok");
});
Then test it like this:
$ curl -X POST --data 'foo=bar' http://localhost:3000/form/form1?url=/abc
You will see the console output like this:
[ name: 'form1' ]
{ foo: 'bar' }
{ url: '/abc' }
So req.body is the right way to access request body, req.query is for read query string of all HTTP methods.

Categories

Resources