Sending Search parameters in get request for angular 4 - node.js

I've searched the web. I found a couple of things but I wasn't able to understand anything out.
I'm trying to send a get request from my angular to Node.js server. I want to send some search parameters for the my server. and it searches then returns the documents.
I'm tring this function to get send the request. But I don't know how to ad parameters beside this request.
GetCases(){
return this.http.get('/api/saleCases')
.map((response:Response)=>response.json());
}
In the server side
router.get('/saleCases', function(req, res){
console.log('get request for all cases');
Case.find({}).exec(function(err, cases){
if(err){
console.log("error retriving videos");
}else{
res.json(cases);
}
});
});
Can you help me to add the parameters in angular and read them in node.js? Or is there any kind of way that you can suggest me to use?

In Client side, first init your search parameters, something like:
const searchParams = {
params: {
param1: val1,
param2: val2,
...
}
}
then send your request to Server side like:
return this.http.get('/api/saleCases', searchParams)
In Server side you can access the params, using:
router.get('/saleCases', function(req, res){
const param1 = req.query.param1;
const param2 = req.query.param2;
});

Related

Unable to get data from React App to Node server

So Am unable to make a search function i want to get a variable from search field and show the results that matched but am constantly getting this error
variable undefined when i try to console.log it in the node server
Edit-- i have already changed the axios.post to axios.get
app.get(`/search/`, (req, res) => {
let {name} =req.body
var Desc = name
console.log(name)
var Op= Desc+'%'
const q = "SELECT * FROM taric where Description LIKE ? ";
con.query(q,[Op], (err, search) => {
if (err) {
console.log(err);
return res.json(err);
}
console.log(search);
return res.json(search);
});
});
As you can see you are making POST request from frontend where as there is no POST request route to handle your request. As you have make route of GET for fetching the data from backend you need to make GET request from frontend as well. So you need to do as below:
axios.get(`your_endpoint_route_goes_here`);
instead of this:
axios.post(`your_endpoint_route_goes_here`, requestBodyObj);
HTTP methods are not the same.
You are using app.get in the server while triggering a POST call from your client.
axios.post <-----> app.get
(There is no route for POST call which client is expecting)

Axios - send get request with url + variable

This must be a stupid question, but I'm just starting and would appreciate any help!
So I have this code to get query parameter:
app.get('/', (req, res) => {
var code = req.query.code;
console.log(code);
And when I go to http://localhost:3000/?code=123, I get the code value in console, so it works fine.
Now, I need to send a GET request and add the value of the var code, this is where I'm stuck.
Let's say, I should send a GET request to 'http://testtesttest123.com/' + var code + 'hi'.
How can I do this?
I've tried this way and some other ways, but nothing worked:
axios.get('http://testtesttest123.com/?&code=', {params: {code}}, '&hi')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
});
Thank you in advance!
The axios.get call should look like this.
axios.get('http://testtesttest123.com/?code=' + code + '&hi')
With code = 123, this will call the URL http://testtesttest123.com/?code=123&hi.
Use the params config to send through query parameters. To support your empty hi parameter, you can include it in the URL string
axios.get("http://testtesttest123.com/?hi", {
params: { code }
})
For a code value of 123, this will perform a GET request to
http://testtesttest123.com/?hi&code=123
It will also ensure that the code value is made safe for use in URLs

how to repeat get request every values change

I have codes like
app.post('/zamansecimi',(req,res)=>{
{
zamansecimim(req.body.baslangic,req.body.bitis)
res.render('./dist/rapor.ejs')
}});
function zamansecimim (bas,bit) {
app.get("/zamansecimi2", function (req, res) {
data2="select * from raporlama where oncekizaman between $1 and $2"
var query = connection2.query(data2,[bas,bit] ,
function(err, result) {
if(err) throw err;
res.send(httpResponse(result.rows));
});
})
}
In these codes I want to change get result every post request but I have a problem with get request these values never change when I send to 2 or 3 ...request. First request is working.
Where is my mistake?
thank you for your help
Each request sent to the server can only have one response, and you can't trigger a GET request inside a POST request on the server and expect the response to that request to go back to the browser. Without the whole app, I can't tell you the best way to do what you want, but I'd suggest you have one response on the server like this:
app.post('/zamansecimi',(req, res)=>{
const bas = req.body.baslangic;
const bit = req.body.bitis;
const query="select * from raporlama where oncekizaman between $1 and $2";
connection2.query(query,[bas,bit], function(err, result) {
if(err) throw err;
res.send(httpResponse(result.rows));
});
});
That will at least ensure you get the correct data back to the browser. It does not seem to me like rapor.ejs needs re-rendering since nothing has changed on the server with the POST request. But honestly I can't tell what's going on from the code provided.

Trouble adding item with PUT to dynamodb table: node.js aws-sdk

I am attempting to add an item to an existing dynamodb table using a PUT request. I have tried several variations of the code including using the .put as well as the .putItem functions. When I hard-code the url into the brower I get the following error:
Cannot GET /add-student?student_id=5&name=carl
When I cut the exact url which gave me this error and paste it into an api testing app, Postman, it works perfectly. I am well aware that the error says that I attempted a GET request, but I don't know what is wrong with my code.
Here's my code.
app.put('/add-student', function (req, res) {
var params = {
TableName : "student",
Item:{
"student_id" : {"N": req.query.student_id},
"name" : {"S": req.query.name}
}
}
dynamodb.putItem(params, function(err, data) {
if(err)
console.log(err);
else
console.log(JSON.stringify(data));
});
});
What might be causing this to be interpreted as a get request? Any help is much appreciated.
By default, when an URL is hit from the browser, the request will be send as HTTP GET request. You can't send other than GET request from browser directly without using plugins or tools.
This is the main reason for using tools like POSTMAN or any other plugins like Firefox plugins to test the REST services that works on different HTTP methods like POST, PUT etc.
1) I think when you hit the URL from POSTMAN, you would have selected the PUT method.
2) If you select the GET method in POSTMAN, you will get the same error.
See the screenshot below. Get request send from POSTMAN throws the same error.
GET request from POSTMAN:-
PUT request from POSTMAN:-
Request send from browser:-
My code is same as yours expect table name:-
app.put('/add-movie', function (req, res) {
var params = {
TableName:"Movies",
Item:{
"yearkey": {"N" : req.query.yearkey},
"title": {"S" : req.query.title}
}
};
dynamodb.putItem(params, function(err, data) {
if(err) {
console.log(err);
res.send("Put is failed...");
}
else {
console.log(JSON.stringify(data));
res.send("Put is successful...");
}
});
});

socket.emit issue into post method

i want to send datas in same client (not all clients) with this code;
app.post("/search", function(req, res) {
//some other codes
//if database saved {
io.sockets.emit('preview-post', {title: "blabla" });// io variable was declared as GLOBAL
// } database saved end.
res.send({bla:bla});// response end before database saving process
});
this sample is working ! but it sends to all clients , How can i emit data to same opened browser(same client) ?
Second Question is: Are there any alternative ways to do this scenario?
My algorithm is post method fired > async call to an api > response end and page loaded on client > async call to an api is still continue > if async call is finished > send alert to client . But How? i wanted to do it wiht socket .io , if i use your 3.part , it'll work , can i do this scenario any other way?
This indeed sends to all sockets.
There are a couple ways to achieve what you are looking to do. The first way is to do something like this on the server:
io.on('connection', function(socket) {
socket.on('search', function(*/ client supplied arguments /*){
socket.emit('preview-post', {title: "blabla" });
});
});
If you are insistent on using a post request, and then sending it back to the client, there are two ways to achieve this.
The easiest way, if you only need to respond to this response, is just send a standard response from node, and let the client handle it:
res.send({
event: 'preview-post',
payload: {title: "blabla" }
});
This removes socket.io's event system, so if you are insistent on using socket.io to send this event back to the same client, you are going to need to use cookies. Express and the module cookie-parser make this easy for you.
Once you have this setup, inside your request you could do something like this:
app.post("/search", function(req, res) {
var socket = findSocketByCookie(req.cookies.myUniqueCookie);
socket.emit('preview-post', {title: "blabla" });
});
function findSocketByCookie(cookie) {
for(var i in io.sockets.connected) {
var socket = io.sockets.connected[i];
if(socket.handshake.headers.cookie.indexOf(cookie) !== -1){
return socket;
}
}
}

Resources