Error 404: post request with Axios and Netifly - javascript

Maybe you can help me with the following problem.
I'm currently working on a project.
Github Project // On Netifly
On the client side, I'm using Axios to perform a post request with route /getContent. Once on the server, the content is sent to a third party API to perform analysis. The Response is then send back to the client side.
Everything is working well locally but when deploying the project on Netifly, I have an error 404 when the browser is targeting that route `/getContent'
POST request on the client Side:
const getData = async (txt) => {
const response = await axios.post("/getContent", { txt });
return response;
};
On the server side with express
/**
* MeaningCloud Object
* main param + url
*/
const meaningCloudReq = {
params: {
key: null,
lang: "uk",
txt: null,
txtf: "plain",
},
url: `https://api.meaningcloud.com/sentiment-2.1`,
getData: async function () {
const { params } = this;
const response = await axios.get(this.url, { params });
return response.data;
},
};
const callApi = async (req, res) => {
const { txt } = req.body;
const key = process.env.API_KEY;
const params = { ...meaningCloudReq.params, txt, key };
const requestApi = { ...meaningCloudReq, params };
try {
const data = await requestApi.getData();
res.send(data);
} catch (error) {
const status = {
status: "500",
msg: "Request did not go throught, contact support.",
};
res.send({ status });
}
};
app.post("/getContent", callApi); // the getContent route
Yet, I kept receiving the following error:
XHR POST https://fervent-rosalind-abbe0e.netlify.app/getContent
[HTTP/2 404 Not Found 1072ms]
Let me know if you have any idea about what's going on.

Related

TypeError when instantiaing SpotifyWebApi object

im trying to write a bot to do some playlist handling in spotify. I'm using the spotify-web-api-node package : https://github.com/thelinmichael/spotify-web-api-node
I installed the package and whenever I try to create an object with the following code:
const SpotifyWebApi = require('spotify-web-api-node');
const spotifyApp = SpotifyWebApi();
I keep getting this error:
this._credentials = credentials || {};
^
TypeError: Cannot set properties of undefined (setting '_credentials')
this is the contructor signature in the src file:
constructor(credentials?: Credentials);
Any thoughts ?
You need an access-token for access API call.
In the documentation,
If you've got an access token and want to use it for all calls, simply use the API object's set method. Handling credentials is described in detail in the Authorization section.
spotifyApi.setAccessToken('<your_access_token>');
Demo code: get access token then get Elvis' albums
const SpotifyWebApi = require('spotify-web-api-node');
const axios = require('axios')
const getToken = async () => {
try {
const response = await axios.post(
url = 'https://accounts.spotify.com/api/token',
data = '',
config = {
params: {
'grant_type': 'client_credentials'
},
auth: {
username: '<your client id>',
password: '<your client secret>'
}
}
);
return Promise.resolve(response.data.access_token);
} catch (error) {
return Promise.reject(error);
}
}
getToken()
.then(token => {
const spotifyApi = new SpotifyWebApi();
spotifyApi.setAccessToken(token);
// Passing a callback - get Elvis' albums in range [0...1]
spotifyApi.getArtistAlbums('43ZHCT0cAZBISjO8DG9PnE', { limit: 2, offset: 0 }).then(
(data) => {
console.log('Artist albums', data.body);
},
(err) => {
console.error(err);
}
);
})
.catch(error => {
console.log(error.message);
});
Result

How to improve sequential promises execution and force fulfillment

This code is being used in a Sveltekit web application.
In the first step I get a user jwt token from an api like : dashboard.example.com/auth/local
and in the second step I'm using the response of the first api call to get full information from an api endpoint like this : example.com/api/users/token
This is an endpoint in an Sveltekit application:
import { json as json$1, error } from '#sveltejs/kit';
import axios from 'axios';
import md5 from 'md5';
import { SITE_ADDRESS } from '$lib/Env';
let userToken;
/** #type {import('#sveltejs/kit').RequestHandler} */
export async function POST({ request }) {
const bodyData = await request.json();
let identifier = bodyData.data.identifier;
let password = bodyData.data.password;
let loginToken = bodyData.data.loginToken;
let newLoginToken = md5(identifier + password + process.env.SECURE_HASH_TOKEN);
let dataResult = await axios
.post(`${import.meta.env.VITE_SITE_API}/auth/local`, {
identifier: identifier,
password: password
})
.then((response) => {
return response.data;
})
.then((response) => {
let userSummaryData = response;
userToken = md5(
userSummaryData.user.username + userSummaryData.user.id + process.env.SECURE_HASH_TOKEN
);
let userCompleteData = axios
.post(`${SITE_ADDRESS}/api/users/${userToken}`, {
data: {
userID: userSummaryData.user.id,
username: userSummaryData.user.username
}
})
.then((response) => {
return {
userJWT: userSummaryData.jwt,
userSummary: userSummaryData.user,
userFullSummary: response.data.userFullSummary
};
});
return userCompleteData;
})
.catch((error) => {
// console.log(' ---- Err ----');
});
if (dataResult && newLoginToken == loginToken) {
return json$1(
{
userJWT: dataResult.userJWT,
userSummary: dataResult.userSummary,
userFullSummary: dataResult.userFullSummary
},
{
headers: {
'cache-control': 'private, max-age=0, no-store'
}
}
);
} else if (dataResult && newLoginToken != loginToken) {
throw error(400, 'Something wrong happened');
}
throw error(401, 'Something wrong happened');
}
This code is work perfectly in localhost. But when I test it on host I get error 401.
and the question is :
Why this works on localhost but doesn't work on the server?
How can I improve this kind of promises (I'd like to use the response of the first api call in the second api call and return both
as a result)

PUT 404 (NOT FOUND) and SyntaxError: Unexpected token < in JSON at position 0

[PUT 404 (NotFound) ][1]
Client-side code
const confirmDeliver = (event) => {
const newQuantity = inventory.quantity - 1;
const updateQuantity = { newQuantity };
const url = `http://localhost:5000/inventory/${inventoryId}`;
fetch(url, {
method: "PUT",
headers: {
"content-type": "application/json",
},
body: JSON.stringify(updateQuantity),
})
.then((response) => response.json())
.then((data) => console.log(data)); };
Server-side code
app.put("inventory/:id", async (req, res) => {
const id = req.params.id;
const updatedQuantity = req.body;
const filter = { _id: ObjectId(id) };
const options = { upsert: true };
const updatedDoc = {
$set: {
quantity: updatedQuantity.quantity,
},
};
const result = await inventoryCollection.updateOne(
filter,
options,
updatedDoc
);
res.send(result);
});
Can anyone tell me why I am getting this error? How can I solve this?
‘Unexpected token <‘ means the response returned is not a valid json. This error may be from a 404 error html page responded from backend.
The request method PUT is different from request methods GET, POST. Make sure the backend has a PUT request method with an appropriate endpoint http://localhost:5000/inventory/your-inventory-id.
To fast test a SUCCESS connection to backend, simply code in backend to return an empty {} json response.

How to delete object from firebase database

I'm trying to figure out how to delete information submitted to the firebase database.
I am trying to delete information under the requests. Example
Here are my actions used to fetch the data:
export default {
async contactArtist(context, payload) {
const newRequest = {
userEmail: payload.email,
message: payload.message
};
const response = await fetch(`https://find-artist-d3495-default-rtdb.firebaseio.com/requests/${payload.artistId}.json`, {
method: 'POST',
body: JSON.stringify(newRequest)
});
const responseData = await response.json();
if (!response.ok) {
const error = new Error(responseData.message || 'Failed to send request.');
throw error;
}
newRequest.id = responseData.name;
newRequest.artistId = payload.artistId;
context.commit('addRequest', newRequest);
},
async fetchRequests(context) {
const artistId = context.rootGetters.userId;
const token = context.rootGetters.token;
const response = await fetch(`https://find-artist-d3495-default-rtdb.firebaseio.com/requests/${artistId}.json?auth=` + token);
const responseData = await response.json();
if (!response.ok) {
const error = new Error(responseData.message || 'Failed to fetch requests.');
throw error;
}
const requests = [];
for (const key in responseData) {
const request = {
id: key,
artistId: artistId,
userEmail: responseData[key].userEmail,
message: responseData[key].message
};
requests.push(request);
}
context.commit('setRequests', requests);
},
};
I'm trying to set up a button that will delete the selected request object.
Your code is sending a POST request, which tells Firebase to generate a unique key. From the documentation on saving data:
POST: Add to a list of data in our Firebase database. Every time we send a POST request, the Firebase client generates a unique key, like fireblog/users/<unique-id>/<data>
The delete a node, send the DELETE verb/method to that path:
const response = await fetch(`https://find-artist-d3495-default-rtdb.firebaseio.com/requests/${payload.artistId}.json`, {
method: 'DELETE'
});

send response from nodejs express to angular app

I am calling an api of sending OTP from my nodejs app. I need to send the response of that OTP Api to the angular app.
my api service on angular look like this:
sendOtp(params): Observable<any> {
return this.apiService.post("/user/send-otp", params)
}
my router on express app look like this
this.router.post("/user/send-otp", userController.sendOtpMessage);
and the code inside userController look like this.
static sendOtpMessage(req, res ,next) {
const phone = req.body.phone;
var http = require("https");
var options = {
"method": "GET",
"hostname": "api.msg91.com",
"port": null,
"path": `/api/v5/otp?mobile=${phone}`,
"headers": {
"content-type": "application/json"
}
};
var callOtpApi = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
console.log(body.toString());
// I need to send this data in response to my angular app ==>> body.toString()
});
});
callOtpApi.write();
callOtpApi.end();
}
OTP Api ref document: https://docs.msg91.com/p/tf9GTextN/e/B1NUt3C8MY/MSG91
It seems that the code above is missing the res.send() to return the data from server. Could you please try with this?
static sendOtpMessage(req, res ,next) {
const serverRes = res;
// Rest of your code
...
var callOtpApi = http.request(options, function (res) {
// Rest of your code
...
res.on("end", function () {
var body = Buffer.concat(chunks);
console.log(body.toString());
// Return data to client
serverRes.send(body.toString());
});
// Rest of your code
...
});
}
You can call the msg91 api using axios
const axios = require('axios');
async function sendOtpTOUser(phone) {
const template = "template _id";
const apiKey = "api_key";
const sendotp = "https://api.msg91.com/api/v5/otp?template_id="+template+"&mobile="+phone+"&authkey="+apiKey;
let request_options1 = {
method: 'get',
url: sendotp
};
let otpResponse = await axios(request_options1);
console.log(otpResponse.data)
return otpResponse.data;
}
it will return the object as
{ request_id: '3166686e7867313634383535', type: 'success' }

Categories

Resources