i have a angular project that calls a firebase function, my firebase function uses fetch to get a xml response, the problem is i dont know how to handle the xml response that needs to be sent back to my angular project..can anyone help please
firebase function
app.post('/provider', bodyParser.json(), async (req, res) => {
const response = await fetch(
'https://api.verify.example.com/identification/report_verification/',
{
method: 'POST',
body: req.body,
headers: {
'Content-Type': 'application/json' ,
'Authorization': 'Token 8c708fe3306f3f55644842a4d1f00561aa57b02e' }
})
const str = await response.text()
res.send(str)
})
Related
I want to hide my API key when I am making a post request from my browser. I need to input a number plate and send the request to the API and the API responds me with details about it. I have managed to get this working with a GET request to another API by using nodeJS but I can't manage to make it work with a post request. Keep in mind the request needs information from my input field in the browser which is the registration number of the vehicle to send me information back about it.
Here is my function in my browser JS file.
const searchBtn = document.getElementById("search-btn")
function startFetch() {
let plate = document.getElementById("plate").value
let reg = {registrationNumber: `${plate}`}
fetch(`https://driver-vehicle-licensing.api.gov.uk/vehicle-enquiry/v1/vehicles`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': `my key is here`,
},
body: JSON.stringify(reg),
})
.then(response => response.json())
.then(response => {
console.log(response);
})
.catch(err => {
console.log(err);
});
};
searchBtn.addEventListener("click", startFetch);
Any help and method would be appreciated. Thanks in advance.
For anyone in the same boat. I have managed to achieve what I want.
Client side JS file:
function startFetch() {
let plate = document.getElementById("plate").value
let reg = {registrationNumber: plate}
fetch(`http://localhost:3000/v`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(reg),
})
.then(response => response.json())
.then(response => {
console.log(response);
})
.catch(err => {
console.log(err);
});
};
And the backend using Express, NodeJS, body-parser and axios
require("dotenv").config()
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const axios = require('axios');
app.use(bodyParser.json());
app.use(express.static("src"))
//Env vars
const API_URL = process.env.API_URL
const API_KEY = process.env.API_KEY
app.post('/v', (req, res) => {
const body = req.body;
// Make a request to the backend API
axios.post(API_URL, body,
{
headers: {
"Content-Type": "application/json",
'x-api-key': API_KEY
}
}
)
.then((response) => {
// Return the response from the backend API to the client
res.send(response.data);
})
.catch((error) => {
// Handle any errors
res.status(500).send(error);
});
});
app.listen(3000, () => {
console.log('API proxy server is listening on port 3000');
});
You are already sending the body.
A very minor modification to you code:
function startFetch() {
let plate = "abc123";
let reg = { registrationNumber: `${plate}` };
fetch(`https://driver-vehicle-licensing.api.gov.uk/vehicle-enquiry/v1/vehicles`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
"x-api-key": `my key is here`,
},
body: JSON.stringify(reg),
}
);
}
startFetch();
You can see your api-key in the header (though you should never send secret via http):
Then in the body (in chrome they call it payload):
How can I change the vanity url code in Discord? My current code returns a 401 error.
Code:
const fetch = require("node-fetch");
setTimeout(async () => {
await fetch('https://www.discord.com/api/v9/guilds/serverID/vanity-url', {
method: 'POST',
headers: { 'Authorization': 'Bot ' + client.token, 'Content-Type': 'application/json'},
payload: JSON.stringify({
"code":"terbo1"
})
})
.then(async res => await res.json())
.then(json => { console.log(json);});
Response:
{ message: '401: Unauthorized', code: 0 }
I don't understand why you need setTimeout however you were using the wrong HTTP method on the request: the correct method is PATCH.
Additionally, payload isn't an option on the Fetch API, use body instead.
const fetch = require("node-fetch");
const endpoint = `https://www.discord.com/api/v10/guilds/${SERVER_ID}/vanity-url`;
await fetch(endpoint,{
method: "PATCH",
headers: {
Authorization: `Bot ${client.token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
code: "terbo1",
}),
});
Edit: As of 01/12/2022 (12/01/22) Discord have now disabled this ability for bots to "manipulate" this request, however, the above script can be used on a User-Account, there are risks of being banned doing so, so it is NOT recommended, use at your own risk.
How to make http request from parse cloud server(back4app) to another server, here i am making request to fake json api https://jsonplaceholder.typicode.com/todos/1
main.js
Parse.Cloud.define("hello", async (request) => {
return Parse.Cloud.httpRequest({
url: 'https://jsonplaceholder.typicode.com/todos/1',
followRedirects: true,
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
}
}).then(function(response){
console.log(response.text)
//return response.text;
//return response.success(response.text)
//resData=100;
return 100; //i am not even returning the response,i am returning a just a const
},function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
})
});
App.js
const cloudFunction=async()=>{
const someVar=10
Parse.Cloud.run('hello').then((response)=>{
console.log(response)
}).catch((error)=>{
console.log(JSON.stringify(error))
})
}
can some body help,thank you good people of stackoverflow
I want to upload image to the database. However, when I use fetch method with 'Content-Type': 'multipart/form-data' but I cannot get the appended data in the server side. It shows that I have no data in the body.
Below is fetching part of the coding
editProfile = () => {
let bodyData = new FormData();
let photo={
uri:this.state.uri,
type:this.state.type,
fileName:this.state.fileName,
}
bodyData.append('transactionCode', 'UPDATEPROFILE');
// bodyData.append('photo', photo);
console.log(bodyData);
fetch(URL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body: bodyData,
}).then((response) => response.json())
.then((responseJson) => {
alert(responseJson);
})
.catch((error) => {
alert(error);
});
}
This is the example of how i check the data at the server side
const custfunction = function (req, res) {
console.log(req.body);
}
When i console.log(req), it shows body:{} is empty
Alright, I just find out the problem. I need to use Multer to handle multipart/form-data in the backend. Thanks a lot.
https://www.npmjs.com/package/multer
When calling render_task_results(render_task_id) looker API from my NodeJS based API using axios I am getting the binary data but when downloading it it is giving me blank PDF.
PFB my code.
const response = await createPdf(TaskID, lookerToken.access_token);
res.set({ 'Content-Type': 'application/pdf', 'Access-Control-Allow-Origin': '*' });
res.status(200).send(response.body);
return res;
export async function createPdf(TaskID, lookerToken): Promise<any> {
return new Promise((resolve) => {
const url = "someurl/api/3.1/render_tasks/" + TaskID + '/results';
const headers = {
'Authorization': 'token ' + lookerToken
};
axios({
headers,
method: 'get',
url: url,
responseType: 'blob'
}).then((response: any) => {
resolve({
body: response.data
//statusCode: response.status,
});
})
});
}