let data = new FormData();
payload = JSON.stringify(payload.unitDoctors);
for (var key in payload) {
data.append(key, payload[key]);
}
axios({
method: "put",
url: apiPath + payload.id,
data: data
})
.then(response => {
commit("updateItem", response.data);
})
.catch(e => {
commit("setErrors", e.response.data);
});
}
when i send formData to api controller unitDoctors(array) always null. Any Idea ?
You are attempting to loop over a string, as you've already called JSON.stringify there. Maybe get rid of that stringification call? It's hard to tell what the actual problem is without seeing your data and the desired result.
Related
I am writing a few API calls which are intertwined and pass on values to each other, there's a get token and store call then an get list of users and store user_id in order for both of those to be forwarded to the third DELETE user api call. The issue im encountering is with the url forming in the delete request. There's a special character in the user_id which is '|' this one. Notably when i pass the JS function decodeURIComponent on it, i get a proper result and the | character. But when calling the decoded variable inside the Cypress request method url option. It keeps ignoring the decode and encoding the character no matter where i try to put decodeURIComponent.
Heres a few examples of the method i tried using
Cypress.Commands.add('deleteCreatedUser', (token, user_id) => {
var userid = decodeURIComponent(user_id)
cy.log(userid)
cy.request({
method: 'DELETE',
url: "https://companydomain.auth0.com/api/v2/users/" + `${userid}`,
auth: {
bearer: `${token}`
}
})
.then((resp) => {
expect(resp.status).to.eq(204)
})
})
Or
Cypress.Commands.add('deleteCreatedUser', (token, user_id) => {
// var new_url = "https://companydomain.auth0.com/api/v2/users/" + `${decodeURIComponent(user_id)}`
// cy.log(new_url)
cy.request({
method: 'DELETE',
url: "https://companydomain.com/api/v2/users/" + `${decodeURIComponent(user_id)}`,
auth: {
bearer: `${token}`
}
})
.then((resp) => {
expect(resp.status).to.eq(204)
})
})
Or
Cypress.Commands.add('deleteCreatedUser', (token, user_id) => {
var new_url = "https://companydomain.auth0.com/api/v2/users/" + `${decodeURIComponent(user_id)}`
cy.log(new_url)
cy.request({
method: 'DELETE',
url: new_url,
auth: {
bearer: `${token}`
}
})
.then((resp) => {
expect(resp.status).to.eq(204)
})
})
All produce the same error message, the cy.log output is correctly:
https://companydomain.auth0.com/api/v2/users/auth0|63c92d19bc49af9a23ede481
but in the cypress request method that fails the URL is:
https://companydomain.auth0.com/api/v2/users/auth0%7C63c92d19bc49af9a23ede481
I am on Cypress version 12.3.0
So the decoding won't work in the Cypress request method, does anyone have a solution for this?
I'm sending a request to get organization data's from API firstly, then ı getting another specific data's -which is "plants"- from another API with sending as a parameter organizationEIC property of my organization data which ı get in the first request. I am doing this to get for each plants of each organizations. What ı want to do is, I need to add organizationEIC property which ı use in the URL query to the response data's which are came as a result of my request. Let me make this clear with one example;
I am sending a request like **https://seffaflik.epias.com.tr/transparency/service/production/dpp-injection-unit-name?organizationEIC=40X000000000104H and as you can see it responses to me with 5 different plant data. I need to add the organizationEIC property -which ı use for get this 5- to this 5 response data and save like this to database to record which organization they are affiliated with. In another request with a different organizationEIC code, maybe it gets 2 plant data, so ı need to add my organizationEIC to this 2 plant data. So how can ı get this data from url to add my result datas in foreach loop?
I hope ı explained my problem clear and easy to understand. So here is my codes;
var datas = []
var result = []
var plantList = []
class App extends Component {
state = {
companies: [],
plants: []
}
componentDidMount() {
fetch('https://seffaflik.epias.com.tr/transparency/service/production/dpp-organization', {
method: "GET",
headers: {
"Content-Type": "application/json",
'X-Requested-With': 'XMLHttpRequest'
}
})
.then(response =>
response.json())
.then(async resultJson => {
this.setState({
companies: resultJson.body.organizations,
})
await this.getPlants(resultJson.body.organizations) //first get org. datas and send as param.
});
}
getPlants = async (items) => {
const data = await Promise.all(items.map((plant) => { //getting plants for each organization
return fetch(`https://seffaflik.epias.com.tr/transparency/service/production/dpp-injection-unit-name?organizationEIC=${plant.organizationETSOCode}`, {
method: 'GET',
headers: {
"Content-Type": "application/json",
'X-Requested-With': 'XMLHttpRequest'
}
}).then(response =>response.json()) //need some logic for my solution here probably :(
}))
data.forEach(element => {
datas.push(element.body.injectionUnitNames)
});
Array.prototype.push.apply(plantList, this.configure(datas))
this.setState({
plants: plantList
})
}
configure = (units) => {
units.forEach((unit) => {
unit.forEach((item) => {
result.push(item)
})
})
return result
}
I am open for any tips and tricks, thx in advance for your helps and advices :)
Add another then() to your fetch() and map the data with the new property
Something like:
const data = await Promise.all(items.map((plant) => { //getting plants for each organization
const {organizationETSOCode} =plant;
return fetch(`https://seffaflik.epias.com.tr/transparency/service/production/dpp-injection-unit-name?organizationEIC=${organizationETSOCode}`, {
method: 'GET',
headers: {
"Content-Type": "application/json",
'X-Requested-With': 'XMLHttpRequest'
}
}).then(response =>response.json())
.then(data=> data.map(o => ({...o, organizationETSOCode})))
}))
I've tried promise chaining, where my chained var is valid, and my fetch is working with manually key-in data, but I can't get it work by putting the var, the return console log shown blank value
{"code":"success","message":null,"data":[]} or
{"code":"success","message":null,"data":[Array(0)]}.
Any suggestions on what I did wrong in my code?
function anExportFunction(){
fetch(an_API_URL_01,{
method: 'GET',
}).then(function(response) {
return response.text();
})
.then(function(dataIds) {
return fetch(an_API_URL_02,{
method: 'POST',
body: JSON.stringify({
"elementIds" : ['dataIds'],
})
})
.then(response => response.text())
.then(data=> console.log(data))
});
Whereby, the manual input that make this fetch response work with the server is as follow
"elementIds" : ["0001","0002","0003",...]
The console.log(dataIds) is as {"code":"success","message":null,"data":["0001","0002","0003",...]}
I have managed to make a few twerk with the advices provided from both #Nick & #Nisala! Thanks both of the experts providing ideas to contribute the success of solving this!
The key of the problem is that the response fed back from the service provider server is always consist of a few criterions including earlier mentioned Code, Message and Data {"code":"success","message":null,"data":["0001","0002","0003",...]}
In order to feed exact data only content, it is necessarily to filter out the unwanted data, and assure the JSON content feeding the second fetch request, not a JSON.stringify content.
Therefore, the Promise Chain should have been built as below
function anExportFunction(){
fetch(an_API_URL_01,{
method: 'GET',
}).then(response => response.json())
.then(retrieveId => {
const dataIds = retrieveId.data;
return fetch(an_API_URL_02,{
method: 'POST',
body: JSON.stringify({
"elementIds" : dataIds,
})
})
.then(response => response.text())
.then(data=> console.log(data))
});
As the title says what I was trying to do is make a universal function to both do GET and POST calls with one function. However, because when sending a GET call it requires the params entry to contain the data, when sending data via POST it requires the data entry (if I'm not mistaken).
I currently have the following function;
function api(method, call, params){
return new Promise(function(resolve, reject){
axios({
url: call,
method,
params
}).then(function(response) {
var body = response.data;
if(body.status !== 1){
return reject(body.message);
}
resolve(body.response);
}).catch(function(err){
reject(err);
});
});
GET calls work fine as there is the params entry, but for POST calls it stops working. How can I fix this so I have one function to handle both calls?
Another way would be to accept config object as a parameter. Also, you do not need to wrap axios() in a new promiseasaxios()` returns a promise itsef.
function api(config) {
const baseUrl = "http://foo.baz";
const updatedConfig = Object.assign({}, config, {
// If you want to append base url to all api methods.
url: `${baseUrl}${config.url}`
});
return axios(updatedConfig).then(response => {
const body = response.data;
if (body.status !== 1) {
throw new Error(body.message);
}
return body.response;
});
}
Usage:
api({
url: "/user",
method: "get",
params: { id: "xyz" }
}).then(() => { });
or
api({
url: "/tag",
method: "post",
data: { tag: "abc" }
}).then(() => { });
I solved it by just pulling the object into a variable and adding the entry.
Example:
var data = {
url: call,
method
}
if(method.toLowerCase() === 'post'){
data['data'] = params;
}else{
data['params'] = params;
}
axios(data).then(function(response) ...
I have the following data being added to my formData()
let uploadData = new FormData();
uploadData.append("peer-video", this.state.peerVideo);
uploadData.append("peer-video-thumbnail", this.state.peerVideoThumbnail);
uploadData.append("project-video", this.state.projectVideo);
uploadData.append(
"project-video-thumbnail",
this.state.projectVideoThumbnail
);
this.state.documents.forEach(item => {
uploadData.append("documents", item);
});
The uploadData has key value pairs in it, I did formData.entries() to check this. And my axios request is as follows:
export const addProject = data => dispatch => {
axios
.post("/api/portfolio/add-project", data, {
headers: {
"Content-Type": `multipart/form-data`
}
})
.then(res => {
dispatch({
type: ADD_PROJECT,
payload: res.data
});
})
.catch(err => {
dispatch({
type: ADD_PROJECT,
payload: err
});
});
};
And if I go to my payload in the network tab I see this:
{"uploadData":{}}
Any suggestions? Thank you for taking the time to help me.
Edit
I tried the following structure in my axios request and it yielded the same result.
axios({
method: "post",
url: "/api/portfolio/add-project",
data: data,
config: { headers: { "Content-Type": "multipart/form-data" } }
})
When I execute the following
for (let keys of uploadData.entries()) {
console.log(keys);
}
These are the values:
I also noticed on formData docs that
Note: If you specify a Blob as the data to append to the FormData object, the filename that will be reported to the server in the "Content-Disposition" header used to vary from browser to browser.
But i'm not sure if that's what is causing my issue here?
Welp, this is what happens when your eyes stare at a screen too long.
this.props.addProject({
title: this.state.title,
company: this.state.company,
description: this.state.description,
role: this.state.role,
skills: this.state.skills,
uploadData: uploadData
});
Needed to simply be:
this.props.addProject(uploadData)
Thank you #vortex
Looks like you are posting an undefined variable called data rather than your uploadData