Svelte (Express & Axios) - http 500 error on put method - express

I'm at a loss. I have a svelte application (Backend: Express, Frontend: Axios). I have a MongoDB with locations. Locations have an array of bands. And I want to add bands to this array. The backend seems to work fine, at least with Postman it works. But when I try to add a band through the frontend, I get a http 500 error.
This is the back end code:
app.put('/api/locations/:location', async (req, res) => {
let location = req.params.location;
let updatedlocation = req.body;
try {
await client.connect();
const database = client.db('Concerts');
const collection = database.collection('locations');
const query = { locationname: location };
const result = await collection.updateOne(query, { $set: updatedlocation });
if (result.matchedCount === 0) {
let responseBody = {
status: "No Location under the name " + location
}
res.status(404).send(responseBody);
}
else {
res.send({ status: "Location " + location + " has been updated." });
}
} catch (error) {
res.status(500).send({ error: error.message });
}})
This is the method in the frontend:
function addConcert() {
location.concerts.push(chosenband);
console.log("http://localhost:3001/api/locations/" +name);
console.log(location);
axios.put("http://localhost:3001/api/locations/" +name, location)
.then((response) => {
alert("Konzert wurde hinzugefügt");
})
.catch((error) => {
alert("Nope");
console.log(error);
});
}
Info: the {chosenband} comes from a select. This seems to work as well, as the console logs show.
The object is correct and includes the new band:
this is the log from the browser
So the object seems fine. Also the put-url is correct.
But I always get this 500 error
Thankful for any advise!

Found the problem. I didn't instantiate the location correctly. First I instantiated it simply as
let location = {}
, that didn't work. When I instantiated it with all the attributes
let location = {example:"", second:""}
it worked. Thanks for your help

Related

Next.js API's config object is not working on production level

Hy,
I'm working on project. I just want to disable the native bodyparcer of next.js and use formidable's parse for incoming requests. I am sending file and some other data from frontend and saveing file on my file system and other data in mongodb.
I did a following configuration for it in that end point.
export const config = {
api: {
bodyParser: false,
},
}
The full code is here.
const fs = require("fs");
const path = require("path")
const decompress = require("decompress");
import formidable from "formidable";
import connect from "../../../database/connect";
import Proposal from "../../../database/models/propSchema";
const directoryPath = e => path.join(process.cwd(), e),
videosDir = directoryPath("/public/videos")
export default function handler(req, res){
res.setHeader("Content-Type", "application/json");
if(req.method === 'POST')
{
console.log(req.method)
const form = new formidable.IncomingForm();
form.parse(req,(err, fields, files) => {
if(err && !files.file){
return res.status(404).json({status: false, error: "Error: Request is not parsed correctly"})
}
console.log("----------------------------",form._parser.globalOptions.maxFileSize)
console.log(files, fields);
const {client,published} = fields,
id = Math.random().toString(36).substring(2) +
(new Date()).getTime().toString(36);
decompress(files.zipFile.filepath, videosDir + "/" + id)
.then(files => {
console.log(files)
console.log(`Proposal API is called with following queries id:${id} and client:${JSON.stringify(client)}`)
connect().catch(error => console.log(error))
const proposal = new Proposal({id,client,published: published? JSON.parse(published) : true})
proposal.save()
.then(()=>{
res.status(200).json(proposal)
})
})
.catch((err) => {
console.log(err);
const path = `${videosDir}/${id}`;
if(fs.existsSync(path)){
fs.readdirSync(path).forEach((file) => fs.unlinkSync(path + "/" + file));
fs.rmdirSync(path);
}
res.status(400).json({
status: "fail",
info: `${id} cannot be compress and Published`,
err,
});
});
});
}
else{
res.setHeader('Allow', 'POST');
res.status(403).json({status: false , discription: "This method is not allowed." })
}
}
export const config = {
api: {
bodyParser: false,
},
}
I make another endpoint to make code simple to understand and remove all code that is unrelative to this error. The same error is occuring with both endpoints.
export const config = {
api: {
bodyParser: false,
},
}
export default function handler(req, res){
if(req.method !== 'POST')
{
res.setHeader('Allow', 'POST');
return res.status(403).json({status: false , discription: "This method is not allowed." })
}
res.status(200).json({status: true});
};
So, When I run it on my local environment and send data, it works fine but in production, it gives a "413 Request Entity Too Large" error. This is because I think the config object is not working correctly on a production level.
Because 1 MB is the maximum file limit of next.js body-parser and when I try to upload a file less than 1 MB it also works fine in production and local system. But when exceeding that limit it gives that error.
And I also try in my local system to send large files without the above configuration, in this case, it gives the same error.
Is this error in the config object? and who can I solve this error?Please help me also to understand it. Thanks

How to fetch data from an API using express.js

API
(https://api.mosmarts.com/truck/v0/api.php)
The API is scripted in PHP and accepts GET & POST commands and in return it responds back with a JSON response data.
To retrieve data the API requires “functionality” and “action” among other params as show below.
Command for retrieving all truck
Command for retrieving all truck
Payloads
{
"functionality" : "get",
"action" : "get_all_truck"
}
Command to retrieving truck inspection details by id
Payloads
{
"functionality" : "get",
"action" : "get_inspection_history",
"truckId" : "1"
}
NB: you will get truckId from command "get_all_truck" above
What’s expected from you
As the software developer you are tasked to design and develop a web-based backend solution that will have:
Dashboard: -
• Retrieve and indicate total number of trucks
• Retrieve and indicate number of inspection repairs requested 2. List all Trucks: -
• Implement search option
Inspection List: -
• Implement filter by truck
i have some code using express.js bt i get is a 404 error, no data retrieved.
app.js
const apiCallFromRequest = require('./Request')
const apiCallFromNode = require('./NodeJsCall')
const http = require('http')
http.createServer((req, res) => {
if(req.url === "/request"){
apiCallFromRequest.callApi(function(response){
//console.log(JSON.stringify(response));
res.write(JSON.stringify(response));
res.end();
});
}
else if(req.url === "/node"){
apiCallFromNode.callApi(function(response){
res.write(response);
res.end();
});
}
// res.end();
}).listen(3000);
console.log("service running on 3000 port....");
NodeJsCall.js
const https = require('https');
_EXTERNAL_URL = 'https://api.mosmarts.com/truck/v0/api.php';
const callExternalApiUsingHttp = (callback) => {
https.get(_EXTERNAL_URL, (resp) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
return callback(data);
// console.log(JSON.stringify(data));
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
}
module.exports.callApi = callExternalApiUsingHttp;
Request.js
const request = require('request');
_EXTERNAL_URL = 'https://api.mosmarts.com/truck/v0/api.php';
const callExternalApiUsingRequest = (callback) => {
request(_EXTERNAL_URL, { json: true }, (err, res, body) => {
if (err) {
return callback(err);
}
return callback(body);
});
}
module.exports.callApi = callExternalApiUsingRequest;
Hey Gerald you can find a simple response for this kind of question on google.
if you are a real beginner I would propose you the Axios npm.
here is an example of a really simple GET request with axios.
axios.get('https://api.github.com/users/mapbox')
.then(response => {
console.log(response.data.created_at);
});

API Request in Dialogflow Fulfillment (Javascript)

So I'm trying to make a google action using Dialogflow that requires an external API. I've always used jQuery .getJSON() to make API calls, so I had no idea how to do this. After searching this up online, I found a way to do this using vanilla javascript (I also tested the way on my website and it worked fine). The code for that is below:
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
console.log(xmlhttp.responseText);
}
};
xmlhttp.open("GET", "https://translate.yandex.net/api/v1.5/tr.json/translate?lang=en-es&key=trnsl.1.1.20190105T052356Z.7f8f950adbfaa46e.9bb53211cb35a84da9ce6ef4b30649c6119514a4&text=eat", true);
xmlhttp.send();
}
The code worked fine on my website, but as soon as I added it to the Dialogflow, it would give me the error
XMLHttpRequest is not defined
Obviously that happened because I never defined it (using var), except it worked without me doing anything. So then, I tried adding this line
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
to the code, and it stopped giving me the error (because I defined XMLHttpRequest). But then, my code wouldn't work.
TL;DR: How can I make an external API call using Dialogflow fulfillment?
You can use https. But make sure that you upgrade to Blaze Pay(or any other plans) to make external API calls, else you will receive an error such as
Error:
Billing account not configured. External network is not accessible and quotas are severely limited. Configure billing account to remove these restrictions.
Code to make external api call,
// See https://github.com/dialogflow/dialogflow-fulfillment-nodejs
// for Dialogflow fulfillment library docs, samples, and to report issues
"use strict";
const functions = require("firebase-functions");
const { WebhookClient } = require("dialogflow-fulfillment");
const { Card, Suggestion } = require("dialogflow-fulfillment");
const https = require("https");
process.env.DEBUG = "dialogflow:debug"; // enables lib debugging statements
exports.dialogflowFirebaseFulfillment = functions.https.onRequest(
(request, response) => {
const agent = new WebhookClient({ request, response });
console.log(
"Dialogflow Request headers: " + JSON.stringify(request.headers)
);
console.log("Dialogflow Request body: " + JSON.stringify(request.body));
function getWeather() {
return weatherAPI()
.then(chat => {
agent.add(chat);
})
.catch(() => {
agent.add(`I'm sorry.`);
});
}
function weatherAPI() {
const url =
"https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22";
return new Promise((resolve, reject) => {
https.get(url, function(resp) {
var json = "";
resp.on("data", function(chunk) {
console.log("received JSON response: " + chunk);
json += chunk;
});
resp.on("end", function() {
let jsonData = JSON.parse(json);
let chat = "The weather is " + jsonData.weather[0].description;
resolve(chat);
});
});
});
}
function welcome(agent) {
agent.add(`Welcome to my agent!`);
}
function fallback(agent) {
agent.add(`I didn't understand`);
agent.add(`I'm sorry, can you try again?`);
}
let intentMap = new Map();
intentMap.set("Default Welcome Intent", welcome);
intentMap.set("Default Fallback Intent", fallback);
intentMap.set("Weather Intent", getWeather);
agent.handleRequest(intentMap);
}
);
This article is a diamond! It really helped to clarify what's going on and what's required in Dialogflow fullfilments.
A small suggestion is to gracefully catch the error in the connection to the webservice:
function weatherAPI() {
const url = "https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22";
return new Promise((resolve, reject) => {
https.get(url, function(resp) {
var json = "";
resp.on("data", function(chunk) {
console.log("received JSON response: " + chunk);
json += chunk;
});
resp.on("end", function() {
let jsonData = JSON.parse(json);
let chat = "The weather is " + jsonData.weather[0].description;
resolve(chat);
});
}).on("error", (err) => {
reject("Error: " + err.message);
});
});
}

React-native axios with ColdFusion component

I'm trying to send a get request from react native, using axios, to my coldfusion component.
My coldfusion component:
component displayName="react" {
remote any function ajaxLogin(data) returnformat="JSON"{
data = deserializeJSON(arguments.data);
return serializeJSON(login(data));
}
private any function login(data){
loginQuery = new query();
loginQuery.setDatasource("ds");
loginQuery.setName("loginQuery");
loginQuery.addParam(name="UserEmail", value="#arguments.data.userEmail#", cfsqltype="cf_sql_varchar");
loginQuery.addParam(name="UserPW", value="#arguments.data.userPassword#", cfsqltype="cf_sql_varchar");
result = loginQuery.execute(sql="SELECT * FROM Users Where UserEmail = :UserEmail AND UserPW = :UserPW");
rs = result.getResult();
if(rs.recordCount == 0){
return 0;
} else {
return rs.UserID;
}
}
}
My react-native dispatch action:
export const loginUser = ({ email, password }) => {
// login
return (dispatch) => {
dispatch({ type: 'TEST' });
axios.get('https://myserver.com/components/reactNative/react.cfc?method=ajaxLogin', {
params: {
userEmail: email,
userPassword: password
}
})
.then((response) => {
console.log(response.data);
})
.catch((err) => {
console.log(err);
});
};
};
It is returning an error from the catch:
Error: Request failed with status code 500
I am new with axios and react-native. Am I using axios wrong?
Thanks
Status code 500 is a server-side error so you're likely getting a Coldfusion error, check your ColdFusion logs.
Also as you're calling this as a GETrequest you can just open the URL in a browser tab and see if you get any errors dumped to the page (in a development environment)
https://myserver.com/components/reactNative/react.cfc?method=ajaxLogin&userEmail=email&userPassword=password
If this is production then you should see errors in your error logs (somewhere like /var/www/opt/coldfusion_11/cfusion/logs on linux)

PUT inside a POST request in expressJS

after searching and trying a lot of different things, I find myself in front of this problem : I want to post a content and save the id to an object that belongs in another schema, I'm using mongoose.
Project.findByid is finding the good project and if I log project after modification, the item is as I want it but the save part just doesn't work.
My question is : Is it possible to do a PUT action inside of a POST request, I tried to remove the first .save and it's not working either.
app.post('/pages', (req, res) => {
var db = req.db;
var name = req.body.name;
var parent = req.body.parent;
var myId = mongoose.Types.ObjectId();
var new_content = new Content({
name: name,
_id: myId,
})
new_content.save(function (error, item) {
if (error) {console.log(error)}
})
Project.findById(parent, 'content', function (error, project) {
if (error) { console.error(error); }
project.content[name] = myId;
project.save(function (error) {
if (error) {
console.log(error)
}
res.send({
success: true
})
})
})
})
Simply use
app.all(path, callback [, callback ...])
Instead of
app.post
More info here ExpressJS Docs