How to get data from app.post in react.js? - javascript

//server.js
app.post('/trip', function(req,res){
var params = "something";
getResult(params).then((db)=>{
// I want to access variable named "db" in App.js(React), but I don't know how to do.
res.send(db);
res.end();
});
});
I want to access variable named "db" in App.js(React), but I don't know how to do. If I use axios like
//App.js
axios.get('http://localhost:3000/trip').then((response)=>{
console.log(response.data);
})
but "GET http://localhost:3000/trip 404 (Not Found)" prints. How can I solve this problem?

The /trip endpoint is of type post, you should be using axios.post() instead of axios.get().
axios.post('http://localhost:3000/trip',#POST Call Body#)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Refer https://axios-http.com/docs/post_example for more details.

Related

No responses defined for platform: DIALOGFLOW_CONSOLE

I've had this problem for almost a day and I don't know what else to do to solve it.
Dialogflow Fulfillment in Dialogflow ES just doesn't want to make any HTTP calls at all. I'm always getting this error: No responses defined for platform: DIALOGFLOW_CONSOLE
My entired code is below. The function that crash everything is:
function simpleGet(requestUrl) {
axios.get(https://eo1lbzchsaeazi9.m.pipedream.net/)
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
}
function simpleGet(requestUrl) {
axios.get(https://eo1lbzchsaeazi9.m.pipedream.net/)
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
}
sorry, there is some context missing here.
do you see the error message when trying to use fullfilments (ie. one API call to get on a backend an answer to a customer interaction?
Also, another clarifying question - is it Dialogflow ES or CX?
I've seen some developers struggling with this error and some of them fixed it by updating the package for fulfillments as described here: https://github.com/dialogflow/dialogflow-fulfillment-nodejs/issues/322

Socket.io-emit in callback gives SyntaxError: Unexpected end of JSON input

So I'm exporting a callback-function in a module like this:
(function() {
let request = require("request");
module.exports = function GithubApi(url, callback) {
let options = {
uri: url,
headers: {
"User-Agent": "Me",
"Content-Type": "application/x-www-form-urlencoded"
}
};
request(options, function(err, body) {
let context = {
issues: JSON.parse(body.body).map(function(issue) {
return {
title: issue.title,
comments: issue.comments,
};
})
};
callback(context) // The callback
});
};
}());
And this callback works perfectly fine when I'm using it in my GET-request with express.js:
app.get("/", (req, res) => {
let url = "some url";
GithubApi(url, (data) => {
res.render("../some-views", data);
});
});
But when I add a socket-emit, the callback-function returns SyntaxError: Unexpected end of JSON input
app.get("/", (req, res) => {
let url = "some url";
GithubApi(url, (data) => {
io.socket.emit("update", {message: data}); // adding this
res.render("../some-views", data);
});
});
Can't understand why the socket would interfere with the request and return an error with JSON. Can anybody help?
The probablem must be caused by the fact that body.body doesn't contain a valid JSON string.
When you run code like this:
JSON.parse(body.body)
you should always use try/catch because JSON.parse throws exceptions on bad JSON.
See those answers for more details:
Calling a JSON API with Node.js
Node JS ignores undefined check
How to extract inner string from the array string
Node server crashes in parsing JSON
So the problem was with the io.sockets.emit("update", {message: data});. For some reason, that interfered with the request(still don't know why tough). I guess it has something to do with the socket broadcasting to all channels, and that causes some kind of error, read something about it here.
So I changed the call to the callback-function to this:
GithubApi(orgs, repo, token, (data) => {
io.of("/").emit("update", {message: data}); // This line made it work
res.render("../views/home", data);
});

restful API using node not returning anything

In my server.js I do:-
app.post('/app/getSingleOrderDetail', function(req,res,next){
orderController.getSingleOrderDetail(req.body.order_id);
})
then in models
exports.getSingleOrderDetail = function(order_id, res, res) {
Orders.find({'_id':order_id}).exec(function(err,result){
console.log('result: '+result) //it's ok!!
res.json(result);
});
};
I'm expecting the result with this $http call in angularjs
$http({
url: '/app/getSingleOrderDetail',
method: "POST",
data: {'order_id' : id}
}).then(function(response){
console.log(response.data)
vm.sales_detail = response.data;
}).catch(function(response) {
alert('Error!');
console.log(response);
});
Everything is passed correctly but I just couldn't get the data back to client side in angularjs.
In getSingleOrderDetail you're expecting the arguments (order_id, res, res), When you're invoking the function though, you're only passing in a value to the first argument, order_id and nothing for res. Also, you've defined res twice which is going to cause an issue in your code when trying to access res.
You should fix up those issues like so
Route
app.post('/app/getSingleOrderDetail', orderController.getSingleOrderDetail);
Model
exports.getSingleOrderDetail = function(req, res) {
let order_id = req.body.order_id;
Orders.find({'_id': order_id}).exec(function(err,result) {
if (err) return res.status(500).send(err);
console.log('result: ' + result); //it's ok!!
return res.status(200).json(result);
});
};
Just a side note, from the looks of your route name, this wouldn't be considered RESTful, it would be more of an RPC (Remote Procedure Call) style API.

Getting undefined value when trying to access json data

I am fetching some json data from the api http://www.omdbapi.com/?t=batman&y=&plot=full&r=js.
Printing out text in console giving me correct data. However when I am trying to access any of its properties its giving me undefined.
var url = "http://www.omdbapi.com/?t=batman&y=&plot=full&r=json";
request.get(url, function(err, res){
if (this.isMounted()) {
this.setState({data : res.text});
}
}.bind(this));
If I try below one it's printing correct data
console.log(this.state.data);
But if I try below it's giving me undefined.
console.log(this.state.data.Title);
Remove res.text property.Also try to log res in the console and see if its an object
var url = "http://www.omdbapi.com/?t=batman&y=&plot=full&r=json";
request.get(url, function(err, res){
if (this.isMounted()) {
this.setState({data : res});
}
}.bind(this));

Why is my Parse Cloud Code request 'unauthorized?'

I'm trying to run Parse cloud code for the first time from an AngularJS app. I keep getting the Parse.Error 'unauthorized' in my console.log. I've initialized Parse in my application and JS keys. Where am I going wrong?
Angular Code Format:
$scope.runSomething = function () {
Parse.Cloud.run('nameFunction', req.body, {
success: function (result){
},
error: function (error){
console.log(error);
}
})
I derive the req.body for the Parse.Cloud.run from prestanding info in the $scope.runSomething function.
My truncated main.js:
Parse.Cloud.define('nameFunction', function(request, response){
Parse.Cloud.useMasterKey();
//Do Stuff})
I'm sure I'm missing something small but I have no idea what.
It sounds like you're close. Cloud functions (including before/after functions) must call success or error on the response object to properly complete, so...
Parse.Cloud.define('nameFunction', function(request, response){
Parse.Cloud.useMasterKey();
var someParam = request.params.someParam;
doSomePromiseReturningThing(someParam).then(function(result) {
response.success(result);
}, function (error) {
response.error(error);
});
});

Categories