I am trying to get coordinates of locations using Mapbox API via request module in my express app. URL of the request (specific location) is given through html form. It is parsed in the url and the API provides all the information, including coordinates. It looks like this:
app.post("/", function(req, res){
var location = req.body.location;
var url = "https://api.mapbox.com/geocoding/v5/mapbox.places/" + location + ".json?access_token=MY_TOKEN"
request(url, function(error, response, body) {
var data = JSON.parse(body);
var coordinates = data.features[0].geometry.coordinates
Everything works well if I try any location that an API can find and process. But when I tried inserting some random characters through the form the app crashes, giving the error "TypeError: Cannot read property 'geometry' of undefined". Console.log(data) shows that the features element of data object is an empty array [ ].
I tried handling the error by showing message and redirecting when data is undefied, like this:
if (!data.features) {
req.flash("error", "Location not found, please try again.")
res.redirect("/")}
Im at the beginning of my coding journey and this is my first request so I highly appreciate any help, thanks!
Sorry was off on my weekend.
If data.features is an empty array it won't fail the test (!data.features).
You could try something like
if(Array.isArray(data.features) && data.features.length>0){
//code here
}else{
req.flash("error", "Location not found, please try again.")
res.redirect("/")
}
Related
I'm having a problem parsing my JSON request using express, and after many hours of trying to research it, I can't figure out what the problem is.
Here is my code snippet
app.post('/Information', (req, res)=> {
console.log(req.body); // this prints out the exact POST request from Postman
const info = JSON.parse(req.body); // this returns SyntaxError: Unexpected token o in JSON at position 1
let insertQuery = `insert into Information(id, name, number, message)
values(${info.id}, '${info.name}', '${info.number}', '${info.message}')`
client.query(insertQuery, (err, result)=>{
if(!err){
res.send('Insertion was successful')
}
else{ console.log(err.message) }
})
client.end;
})
I know the reason behind the parsing error, trying to parse an 'o', because req.body is an object, but I tried the three methods of accessing properties of an object, and I get 'undefined'. I don't know if this will help, but if I send this POST request { "id":"3", "name":"Mark Zuckerberg", "number":"1112223333", "message":"Welcome to Facebook!" } from Postman, then this is what console.log(req.body) will print out {'{\r\n "id":"3",\r\n "name":"Mark Zuckerberg",\r\n "number":"1112223333",\r\n "message":"Welcome to Facebook!"\r\n}\r\n': ''}. This output looks odd to me because of the (: '') at the end, as it makes it look like there are only 2 properties for some reason and I don't understand why that's happening. I would be glad to try out any ideas you guys have, because I'm really lost right now. Thank you in advance.
so my question is very specific. Whenever I run this bit from my page I get an error if I don't input the CORRECT ID I need to search for in the API. It doesn't know what to do when it doesn't make a valid API call because the query string is incorrect. How do I go about redirecting to a different page WHEN there's an error like that or how do I prevent it from STOPPING the program? I'm assuming there's a try catch in here but I tried it multiple different ways and I'm still confused because it doesn't work. Help please! I'm new to this... Here's the snippet. The request portion of the code is where the error occurs if the "bnetID" is not a valid ID. If it is valid it runs perfectly fine...
// Make a GET request to the /results page (When submit is pressed)
app.get("/results", function(req, res){
// Retrieve bnetID and REGION from the FORM
var bnetID = req.query.bnetID;
var region = req.query.region;
// Replace the # with a -
bnetID = bnetID.replace("#", "-");
// Create the query string
var url = "http://ow-api.herokuapp.com/profile/pc/"+ region +"/"+bnetID;
// Make the API request
request(url, function(err, response, body){
if(err){
console.log(err);
} else {
var playerData = JSON.parse(body);
playerData = findImportantData(bnetID, playerData);
checkIfExists(bnetID, playerData);
res.render("results", {data: playerData});
}
})
});
Why don't you handle what you want to do if there is an error?
if(err){
console.log(err); // change this to whatever you want to do
}
Hello I am trying to put the type value in my mongodb database using rest api. However, it shows an error saying cannot put (404 not found).
app.js
app.put('api/types/:_id', function(req,res){
var id = req.params._id;
var type = req.body;
Type.updateType(id, type, {}, function(err, type){
if(err){
throw err;
}
res.json(type);
});
});
type.js
module.exports.updateType = function(id, type, options, callback){
var query = {_id: id};
var update = {
name: type.name,
description: type.description,
category: type.category
}
Task.findOneAndUpdate(query,update, options, callback);
}
Use '/api/types/:_id' rather than 'api/types/:_id'
One more issue which causes the mentioned error:
Check if there is any typo mistake in the URL which you are trying to access.
In my case, I tried accessing
"/api/users/udpate/:id"
instead of
"/api/users/update/:id"
I have entered udpate instead of update.So express will not be able to find the route which causes this error.
Two solutions can be of this issue:
Can be a typo in endpoints.
Instead of this
"uesr/:userId"
Check for this
"/user/:userId"
Can be a slash missing in starting.
Instead of this
"user/:userId"
Add this slash in starting
"/user/:userId"
Basically what the title says - I've been getting a 404 Not Found on all ids that I enter for "id":
dpd.items.get("id", function(results, error) {
console.log(results);
});
And a 400 Bad Request on any value of "id":
dpd.items.put("id",{category:value},function(results, error){
console.log("Record updated");
});
All the id values exist in the Deployd dashboard, and I am able to make get requests using any category parameters OTHER than ID.
Feels like I've tried everything at this point, please help!
This error can occur if you insert documents through a different client than deployd.
From here:
MongoDB uses ObjectIds as the default value for the _id field if the _id field is not specified ... if a client does not add an _id field, mongod will add an _id field that holds an ObjectId.
Although the IDs created by mongoDB are visible in the deployd dashboard, they are not normal strings (like the IDs generated by deployd) and deployd does not find them when it's looking for a string.
Try to run a query like the following with any other mongoDB client (e.g. Robomongo):
db.yourcollection.find({_id: ObjectId("some_id_you_know_exists_in_collection")})
If it does not throw an error, the id is most likely an ObjectId that was not created by deployd.
Unfortunately, there is no easy fix. (At least not for big collections and complicated apps.)
For SMALL collections I'd suggest to just duplicate the data into a new collection and let deployd create new IDs.
Quick, dirty and untested:
dpd.collection.get({}, function(res) {
_.each(res, function(object){
object.oldId = object.id //add id backup
delete object.id
// post new object without id -> deployd creates a new id
dpd.newcollection.post(object, function(res, err) {
if(err) {
console.log(err);
};
if(res) {
console.log(res);
};
})
});
})
You have to decide for yourself if that works for you.
Deployd create crud API of any collection.
Make sure collection name is correct try to use
http://localhost:PORT/items/id .. if this will also give 404 then open
http://localhost:PORT/dashboard/items/events/
and On dashboard goto dashboard/items/events/ this will open ON GET panel, write there console.log(this.query)
and about 400 request , you write the code console.log(this.body) on
http://localhost:PORT/dashboard/items/events/#put-panel
This is the way to debug your API, deployd have some issue but better framework to create API instantly
I'm getting a 404 error when trying to delete a Twilio phone number via the API.
Here's my code:
var twilioSID = user.numberSID; // PN946a0603c974be563c5916f865be4d0b
var accountSid = '{removed}';
var authToken = '{removed}';
var client = require('twilio')(accountSid, authToken);
client.incomingPhoneNumbers(twilioSID).delete(function(err, deleted) {
if (err){
console.log(err);
} else {
console.log('Deleted from Twilio');
}
});
Here is the error I'm getting in the console:
{
status: 404,
message: 'The requested resource /2010-04-01/Accounts/{removed}/IncomingPhoneNumbers/PN946a0603c974be563c5916f865be4d0b.json was not found',
code: 20404,
moreInfo: 'https://www.twilio.com/docs/errors/20404'
}
The Twilio API doesn't have hardly any documentation for deleting numbers either. Any ideas on why this is not working?
#parkeragee Your solution is working
client.incomingPhoneNumbers(poneNumberSID).delete(function(err, deleted) {
if (err){
console.log(err);
} else {
console.log('Deleted from Twilio');
}
});
They changed it from delete to remove in their node js module.
As of this writing, the function to remove Twilio phone numbers via the API is called remove. If you try to use delete, you should receive the following error:
client.incomingPhoneNumbers(...).delete is not a function
I wasn't able to find any reference in the Twilio API docs; found this by reading the source, Luke.
Here's an example invoking remove:
client.incomingPhoneNumbers(sid).remove()
.then(function(deleted) {
// Success
})
.catch(function(error) {
// Handle error
});
According to their REST API documentation, you can send an HTTP DELETE request to a url like /2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers/{IncomingPhoneNumberSid}. So the URL in the error message looks almost right, except for the .json on the end. Either way it looks like a bug in their code if the phone number is in fact still attached to your account.
My issue was that I was overwriting my production phone nuber numberSID variable with my test phone number. So the user.numberSID; that I was assigning to a variable was for the Twilio test phone numbers. So, when it was searching for that numberSID, it returned a 404.