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)
Related
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.
I've been researching this issue for several hours now and found something odd. Using ExpressJS, Firebase, and React for a small app, and need to call the Firebase Database via the Express Backend, and I also need to make post requests to store data in the database via the Express Backend.
Functionality: I make a post request to the backend to add data to the database. Since Firebase is real time db, the data will immediately reflect on the page.
Problem: The issue is, when I make a post call to the backend and that completes, the page refreshes but the data doesn't show because of this
ERROR: [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
/**
* Add new note to Firebase
* Real-Time Database
*/
app.post('/addNote', (req, res)=> {
var title = req.body.note.title;
var body = req.body.note.body;
var userId= req.body.note.uid;
db.notes.push({
title: title,
body: body,
uid: userId
})
res.send("Success")
})
app.get('/all', (req, res, next)=> {
db.notes.on('value', snapshot => {
return res.send(snapshot.val());
})
})
Possible Solution: I've found that using the code below, I can make a post request, manually refresh the page, and the data will reflect with no header error. I'm trying to code the proper functionality but can't seem to figure out where the code is sending multiple responses with the db.notes.on because I'm only sending res.send one time. The clear difference is (.on listens and updates immediately, while .once requires manual refresh)
/**
* Add new note to Firebase
* Real-Time Database
*/
app.post('/addNote', (req, res)=> {
var title = req.body.note.title;
var body = req.body.note.body;
var userId= req.body.note.uid;
db.notes.push({
title: title,
body: body,
uid: userId
})
res.send("Success")
})
app.get('/all', (req, res, next)=> {
db.notes.once('value', snapshot => {
return res.send(snapshot.val());
})
})
An on("value" listener to Firebase will fire:
straight away with the current value of the data,
and will then later also fire when the data changes.
Since you're sending the data in the response to the client in #1, the response will be closed/finished by the time #2 happens.
By using a once("value" listener this problem doesn't happen, since once() removes the listener after #1.
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;
});
I am trying to make a slack app and to complete Oauth2, I have to send the URI below and get a JSON response back in the body.
The problem is, every time I am trying to use the function request() in my app.get() function, ejs is always trying to go and get my views. Now I tried rendering my specific view for app.get() but then when I use request() again, ejs is again trying to get a view.
How can I redirect to another url from my app.get and receive the JSON. I can use req.redirect() but I don't know how to get the response back.
Please please help! Thanks
app.get('/', (req, res) =>{
var options = {
uri: 'https://slack.com/api/oauth.access code='+req.query.code+'&client_id='+client_id+'&client_secret='+client_secret,
method: 'GET'
}
request(options, (error, response, body) => {
var JSONresponse = JSON.parse(body)
if (!JSONresponse.ok){
console.log(JSONresponse)
res.send("Error encountered: \n"+JSON.stringify(JSONresponse)).status(200).end()
}else{
console.log(JSONresponse)
res.send("Success!")
}
})
})
so I have the following Scenario; I have a private API key that Angular will show in XHR request. To combat this, I decided to use Express as a proxy and make server side requests. However, I cannot seem to find documentation on how to make my own get requests.
Architecture:
Angular makes request to /api/external-api --> Express handles the route and makes request to externalURL with params in req.body.params and attaches API key from config.apiKey. The following is pseudocode to imitate what I'm trying to accomplish:
router.get('/external-api', (req, res) => {
externalRestGetRequest(externalURL, req.body.params, config.apiKey)
res.send({ /* get response here */})
}
You are half way there! You need something to make that request for you. Such as the npm library request.
In your route something like
var request = require('request');
router.get('/external-api', function(req, res){
request('http://www.google.com', function (error, response, body) {
console.log('error:', error); // Print the error if one occurred and handle it
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
res.send(body)
});
})
This allows you to make any type of request using whatever URL or API keys you need. However it's important to note you also need to handle any errors or bad response codes.
The accepted answer is good, but in case anyone comes across this question later, let's keep in mind that as of February, 2020, request is now deprecated.
So what can we do? We can use another library. I would suggest Axios.
Install it and do something like:
const axios = require('axios')
const url = "https://example.com"
const getData = async (url) => {
try {
const response = await axios.get(url)
const data = response.data
console.log(data)
} catch (error) {
console.log(error)
}
}
getData(url)