cypress error while testing file upload to api - node.js

I am testing an api which requires to send an image in the request body but I am getting error,
Here's my code:
it("should register a new litigant/customer", () => {
cy.fixture('testImg1.png', "base64").then(base64 => {
const blob = Cypress.Blob.base64StringToBlob(base64, 'image/png')
const bodyObj = {
email: "customer#customer.com",
password: "123456789",
profilePicture: blob
}
let formData = new FormData()
for (let key in bodyObj){
formData.append(key, bodyObj[key])
}
cy.request({
method: "POST",
url: endpoints.signup.litigant,
headers: { "content-type": "application/x-www-form-urlencoded" },
body: formData,
}).then(res => {
expect(...)
})
})
})
But I am getting this error:
Does anyone know how to fix this??

Related

Can't able to pass user information from website to chatbot using directline in microsoft bot framework with python sdk

I'm trying to pass user name from website to chatbot using directline feature. I'm using python sdk and following the below link.
https://github.com/microsoft/BotFramework-WebChat/tree/master/samples/04.api/a.welcome-event
my js file looks like
(async function() {
var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer <token here>");
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
"user": {
"id": "dl_123"
},
"trustedOrigins": []
});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("https://directline.botframework.com/v3/directline/tokens/generate", requestOptions)
.then(response => response.text())
.then(result => {console.log(result)
var token = JSON.parse(result).token
console.log("token",token)
const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
dispatch({
type: 'WEB_CHAT/SEND_EVENT',
payload: {
name: 'webchat/join',
value: "user_name_here"
}
});
}
return next(action);
});
window.WebChat.renderWebChat(
{
directLine: window.WebChat.createDirectLine({ token }),
store
},
document.getElementById('webchat')
);
document.querySelector('#webchat > *').focus();
})})().catch(err => console.error(err));
and my python code looks like
if turn_context.activity.name != "webchat/join":
response = MessageFactory.text(f"Hai {turn_context.activity.value} Welcome to Portal")
but it show none in the place of turn_context.activity.value
I actually want to print username passed from js file here. how to do that.

Axios POST request to Twillio returns with an Authentication Error?

in Node.js, I am trying to send a POST request with Axios to Twilio and send an SMS message to my phone. But I am getting an 'error: Authentication Error - No credentials provided ? Here is the code:
const body = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
Body: 'hi from vsc',
To: toNumber,
From: fromNumber,
};
const headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
Authorization: `Basic ${accountSID}:${authToken}`,
};
exports.axios = () => axios.post(`https://api.twilio.com/2010-04-01/Accounts/${accountSID}/Messages.json`, body, headers).then((res) => {
console.log(res, 'res');
}).catch((err) => {
console.log(err);
});
I also tried to use the same parameters with POSTMAN and the POST request is successful. I also tried to encode my authorization username and password to Base 64, but with no success.
I wrote to Twilio customer help but haven`t received any replies yet.
Axios makes an auth option available that takes an object with username and password options. You can use this with the username set to your account SID and password set to your auth token.
The headers object should be sent as the headers parameter of a config object in the third parameter to axios.post. Like so:
const params = new URLSearchParams();
params.append('Body','Hello from vcs');
params.append('To',toNumber);
params.append('From',fromNumber);
const headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
};
exports.axios = () => axios.post(
`https://api.twilio.com/2010-04-01/Accounts/${accountSID}/Messages.json`,
params,
{
headers,
auth: {
username: accountSID,
password: authToken
}
}
}).then((res) => {
console.log(res, 'res');
}).catch((err) => {
console.log(err);
});
Headers is actually a field of config, try something like this:
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
Authorization: `Basic ${accountSID}:${authToken}`,
}
}
axios.post(URL, data, config).then(...)
Or this (general example calling a Twilio endpoint)
const axios = require('axios');
const roomSID = 'RM1...';
const participantSID = 'PA8...';
const ACCOUNT_SID = process.env.ACCOUNT_SID;
const AUTH_TOKEN = process.env.AUTH_TOKEN;
const URL = "https://insights.twilio.com/v1/Video/Rooms/"+roomSID+"/Participants/"+participantSID;
axios({
method: 'get',
url: URL,
auth: {
username: ACCOUNT_SID,
password: AUTH_TOKEN
}
})
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.log(error);
});
Working code:
const params = new URLSearchParams();
params.append('Body','Hello from vcs');
params.append('To',toNumber);
params.append('From',fromNumber);
exports.axios = () => axios.post(
`https://api.twilio.com/2010-04-01/Accounts/${accountSID}/Messages.json`,
params,
{
auth: {
username: accountSID,
password: authToken,
},
},
).then((res) => {
console.log(res, 'res');
}).catch((err) => {
console.log(err);
});
The previous solutions did not work for me. I encountered either the Can't find variable: btoa error or A 'To' phone number is required..
Using qs worked for me:
import qs from 'qs';
import axios from 'axios';
const TWILIO_ACCOUNT_SID = ""
const TWILIO_AUTH_TOKEN = ""
const FROM = ""
const TO = ""
const sendText = async (message: string) => {
try {
const result = await axios.post(
`https://api.twilio.com/2010-04-01/Accounts/${TWILIO_ACCOUNT_SID}/Messages.json`,
qs.stringify({
Body: message,
To: TO,
From: FROM,
}),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
auth: {
username: TWILIO_ACCOUNT_SID,
password: TWILIO_AUTH_TOKEN,
},
},
);
console.log({result});
} catch (e) {
console.log({e});
console.log({e: e.response?.data});
}
};

Axios FormAppend post method and node.js

I trigger / upload in node.js by calling the submit function inside a class. But in Node.js, req.body is empty. In fact, I append data to FormData in the submit function and send it to node.js. Where am I doing the problem?
Class
submit(){
const data = new FormData()
data.append('file', this.state.selectedFile)
data.append('ID', uniqid())
let url = "http://localhost:5000/upload";
axios({
method: "POST",
url: url,
data: data,
headers: {
"Content-Type": "application/json"
}
}).then(res => {
});
}
Node.js
app.post('/upload', (req, res) => {
axios.post('https://....php', req.body, {
}).then(function (response) {
}).catch(function (error) {
console.log('errorserver', error);
});
});
Try to put file after text like this.
submit(){
const data = new FormData()
data.append('ID', uniqid())
data.append('file', this.state.selectedFile)
let url = "http://localhost:5000/upload";
axios({
method: "POST",
url: url,
data: data,
headers: {
"Content-Type": "application/json"
}
}).then(res => {
});
}

Cloudconvert - Invalid signature error when using request-promise to upload via API

I'm attempting to upload a pdf through the cloudconvert API using nodeJS and request-promise. The request to get the upload URL and parameters is successful, but when I attempt to pass the data I get a 401 - "FormPost: Invalid Signature" error, even though I'm using the signature returned from the first request.
...
pdfToPng: function(pdfBuffer, apiKey) {
return new Promise(async (resolve, reject) => {
const cloudConvert = new CloudConvert(apiKey);
let response = JSON.parse(
await request.post('https://api.cloudconvert.com/v2/import/upload', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-type': 'application/json',
},
}));
let fileUrl = response.data.result.form.url;
let params = response.data.result.form.parameters;
let fileUpload = await request.post({
url: fileUrl,
formData: {
"expires": params.expires,
"max_file_count": params.max_file_count,
"max_file_size": params.max_file_size,
"signature": params.signature,
"file": {
value: pdfBuffer.toString('base64'),
options: {
filename: 'invoice.pdf',
contentType: 'application/pdf'
}
}
}
}).catch((err) => {
console.log('ERROR UPLOADING FILE: ', err); //<-- 401 Error here
reject(err);
})
console.log('FILE UPLOAD RESPONSE: ', fileUpload);
...
You need to pass all parameters of response.data.result.form.parameters to formData, not just the named ones:
let fileUpload = await request.post({
url: fileUrl,
formData: {
...response.data.result.form.parameters,
"file": {
value: pdfBuffer.toString('base64'),
options: {
filename: 'invoice.pdf',
contentType: 'application/pdf'
}
}
}

How to show the success response from node server on react-redux framework

I am making a demo react-redux app for the basic understanding of redux and its server is made on nodeJS. I have made a simple form which gets submitted and the server response is res.send('FORM SAVED'). In front-end, I make the post request but is not able to see the response that returns, be it the success response.
My server controller that responds when form details are saved.
export const postData = (req, res) => {
let p = new PostData();
p.name = req.body.name;
p.emp_id = req.body.emp_id;
p.age = req.body.age;
p.dept = req.body.dept;
p.phone = req.body.phone;
p.gender = req.body.gender;
p.save(((err) => {
if (err){res.send(`Error in uploading: ${err}`);}
else {res.send('Form saved');}
}));
}
This is my action:-
export const createPost = postData => dispatch => {
fetch(`${Config.address}/post`, {
method: 'POST',
headers:{
'Content-Type': 'application/json'
},
body: JSON.stringify(postData)
})
.then((post) => {
console.log('post:', post);
dispatch({
type: NEW_POST,
payload: post
})
})
}
This is how I call this in component after clicking submit:-
onSubmit = (e) => {
e.preventDefault();
let postData = {
name: this.state.name,
emp_id: this.state.emp_id,
dept: this.state.dept,
gender: this.state.gender,
age: this.state.age,
phone: this.state.phone
}
this.props.createPost(postData);
}
I want to get the response string ('Form saved') but I don't know how to read that. Can anyone help? Thanks in advance
fetch returns a raw response object. To get an expected data you should call a .json() method on raw response object which is returned by fetch, like below:
export const createPost = postData => dispatch => {
fetch(`${Config.address}/post`, {
method: 'POST',
headers:{
'Content-Type': 'application/json'
},
body: JSON.stringify(postData)
})
.then(response => response.json()) // add this line
.then((post) => {
console.log('post:', post); // you should get an object with `Form saved` or something similar to it
dispatch({
type: NEW_POST,
payload: postData // replace it to the input parameter
})
})
}
Using async/await it becomes more readable:
export const createPost = (postData) => async (dispatch) => {
// send postData to server
const rawResponse = await fetch(`${Config.address}/post`, {
method: 'POST',
headers:{
'Content-Type': 'application/json'
},
body: JSON.stringify(postData)
});
// we are done with server but we need one more step
// turn a raw response to readable JS object
const message = await rawResponse.json()
// message from server response
console.log('Message ', message);
// store same object as we sent to server in redux store
dispatch({ type: NEW_POST, payload: postData });
}
Hope it helps

Resources