I have some php code that runs curl commands. However the company I work for is switching over to nodejs and I am not sure how to replicate the request in the same way in node. Or I would even be happy if I could replicate the request on the front end using axios. I don't really care how I do i I just need to replicate the request in the exact same way.
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPHEADER => array(
'Authorization: Token '.$token
),
CURLOPT_URL => 'https://myWebsite.com/api/led/contents/',
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
url => '#bannerStockUpload/'.$assetName.'/'.$assetName.'_'.$dimensions[1].'.mp4',
thumbnail => '#bannerStockUpload/'.$assetName.'/'.$assetName.'_thumb.jpg',
type => 'video',
width => $dimensions[0],
height => $dimensions[1],
duration => $dur,
name => $assetName."_".$dimensions[0]."x".$dimensions[1]."mp4"
)
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
you can install axios via npm then:
const axios = require('axios');
const data = {
url: '#bannerStockUpload/'.$assetName.'/'.$assetName.'_'.$dimensions[1].'.mp4', // chnage $assetName to js variable
thumbnail: '#bannerStockUpload/'.$assetName.'/'.$assetName.'_thumb.jpg',
type: 'video',
width: $dimensions[0], // change dimension to js variable
height: $dimensions[1], // change dimension to js variable
duration: $dur,
name: $assetName."_".$dimensions[0]."x".$dimensions[1]."mp4"
}
const headers = {
headers: {
Authorization: 'Token ' + $token // add javascript token
}
}
// Make a request for a user with a given ID
axios.post('https://myWebsite.com/api/led/contents/', data, headers)
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
Related
I am trying to get the domain from the request in nodejs, the request originates from PHP and when I get origin in Nodejs I get undefined.
This is my code in PHP: (domain1.com)
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://myNodedomain.com/sendAlert',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HEADER => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => array('token' => '3242342332'),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
This is my code in NodeJs: (mynodedomain.com)
app.post('/sendAlert', async (req, res) => {
console.log(req.get('host'));
console.log(req.get('origin'));
});
The desired result is:
https://domain1.com/
Any solution?
I'm not super familiar with PHP, but adding something like this might work:
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Origin: domain1.com']);
I wrote a function that receives my list from the server (NODEJS) in the REACT language
getList = () => {
const request = new Request('http://localhost:3000/api/get');
fetch(request, {method: 'GET',mode: 'no-cors',
})
.then((response) => console.log("response", response.JSON()));
}
The request is being made but the returned value I receive in CONSOLE.LOG is:
response Response {type: "opaque", url: "", redirected: false, status: 0, ok:
false, …}body: (...)bodyUsed: falseheaders: Headers {}ok: falseredirected: falsestatus:
0statusText: ""type: "opaque"url: ""__proto__: Response
This is the code on the server:
const MyList=[
{id:1,name:'to do list'},
{id:2,name:'to sleep'},
]
app.get('/api/get',(req,res)=>{
res.send(MyList);
});
Where is the values of the list returned from the server ???
The data from the server can be accessible from response.body, however response.json() returns a promise, so you will have to do something like this:
getList = () => {
const request = new Request('http://localhost:3000/api/get');
fetch(request, {method: 'GET',mode: 'no-cors'})
.then((response) => response.json().then(json => {
console.log(json.body);
});
}
I added .json to response:
getList = () => {
const request = new Request('http://localhost:3000/api/get');
fetch(request, {method: 'GET',mode: 'no-cors' })
.then((response) => console.log("response", response.json()));
}
and received the following error:
TobuyList.js:30 Uncaught (in promise) SyntaxError: Unexpected end of input
at TobuyList.js:30
In your server, change res.send to res.json
On the client side (taken from mozilla docs):
fetch('http://localhost:3000/api/get', { mode: 'no-cors' })
.then(response => response.json())
.then(data => console.log(data));
As a POC I would like to make pictures of my receipts (gas, shop etc) and use a chatbot to send them to my accounting software. My problem has to do with the sending of the collected receipt (an image) to the accounting software using its API.
The first part (getting the attachment) results in an Arraybuffer with an image. I used one of the NodeJS samples for that (nr 15).
const attachment = turnContext.activity.attachments[0];
const url = attachment.contentUrl;
let image;
axios.get(url, { responseType: 'arraybuffer' })
.then((response) => {
if (response.headers['content-type'] === 'application/json') {
response.data = JSON.parse(response.data, (key, value) => {
return value && value.type === 'Buffer' ? Buffer.from(value.data) : value;
});
}
image = response.data;
}
).catch((error) => {
console.log(error);
});
I am struggling with the second part. Posting the image to the accounting software
const requestConfig = {
headers: {
'Authorization': 'Bearer ' + accessToken,
'Content-Type': 'application/x-www-form-urlencoded'
}
};
axios.post(postUrl, image, requestConfig)
.then((response) => { console.log(response); }
).catch((error) => {
console.log(error);
});
};
This results in 400. bad request. Probably the API needs a file and I cannot just send the buffer. I tested with Postman and the request is accepted by using application/x-www-form-urlencoded (by using a locally stored image file).
What is best practice to post an image retrieved in a bufferarray?
I think your comment is right on the money that you need to convert it to a file first. The channel isn't an issue because the file will be stored wherever the bot is hosted. The Attachments Sample actually has this code, which gets you close:
fs.writeFile(localFileName, response.data, (fsError) => {
if (fsError) {
throw fsError;
}
// Send the file
const url = '<yourApiUrl>';
const formData = new FormData();
formData.append('file',fs.createReadStream('<pathToFile>'), { knownLength: fs.statSync('<pathToFile>').size });
const config = {
headers: {
...formData.getHeaders(),
'Content-Length': formData.getLengthSync()
}
};
axios.post(url, forData, { headers });
});
I'm not super confident in the // Send the file section only because I can't test against your API. I got most of the code from here.
I have a working image-upload front/back-end code working. Now I would like to be able to GET the image from server after it is uploaded.
The problem is that the images must be behind an authenticated route, where user has to pass jwt token in header or body.
When i try to fetch the image like this:
fetch(imageURL, {
method: 'GET',
headers: {
'x-access-token': localStorage.getItem('token')
}
I just get a Form object as the response:
<img alt="Your pic" src="[object FormData]">
Would there be some way to get the image into HTML 'img' tag other than just pasting the url in 'src' attribute, since it leads to 401 (Unauthorized)
You can try the following snippet:
const myImage = document.querySelector('img');
// I make a wrapper snippet which will resolve to a objectURL
function fetchImage(url, headers) {
return new Promise((resolve, reject) => {
fetch(url, headers)
.then(response => response.blob()) // sending the blob response to the next then
.then(blob => {
const objectUrl = URL.createObjectURL(blob);
resolve(objectUrl);
}) // resolved the promise with the objectUrl
.catch(err => reject(err)); // if there are any errors reject them
});
}
fetchImage(imageUrl, {
method: 'GET',
headers: {
'x-access-token': localStorage.getItem('token')
}
})
.then(objectUrl => myImage.src = objectUrl)
.catch(err => console.log(err));
An other example for you to try you can find at:
https://davidwalsh.name/convert-image-data-uri-javascript
So i'm trying to authenticate in my angular application. I attended headers and created an stringified body. I also looked at serveral other forum post about sending post requests in postman but i cannot get it working.
getToken()
{
console.log('started getting of token');
//get username and password from local storage
//Send username and password via body
let headers = new Headers();
let body = JSON.stringify({
name: 'test',
password: 'test'
});
headers.append('Content-Type', 'application/x-www-form-urlencoded');
this.jwt = this.http.post('http://localhost:8080/api/authenticate/', {
headers: headers,
body: body
}).map(res => res.text()).subscribe(data => console.log(data));
}
So above is my code. I know it might be a little silly thing but I cannot get it working.
I get the error that the user cannot be found. That happens when the username is wrong, and when the username does not exsist in the database. So that a little extra tricky as well.
Who knows what the stupid mistake is that I made?
Add this code in your service.ts file.
import { Http, URLSearchParams} from '#angular/http';
getToken()
{
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let body = new URLSearchParams();
body.set('name', test);
body.set('password', test);
return this.http.post("http://localhost:8080/api/authenticate/", body, headers).map(response => response.json());
}
Use following code to send post request
this.jwt = this.http.post('http://localhost:8080/api/authenticate/',body,headers).map(res => res.text()).subscribe(data => console.log(data));
This code is what I use for post request
send_request_post(url: String, data:{})
{
var headerPost = new Headers
({
'Content-Type' : 'application/json ;charset=utf-8'
})
return this.http.post(url, JSON.stringify(data), {headers: headerPost})
.toPromise()
.then
(
response =>
{
console.log(response);
}
)
}