Axios url won't preserve encoded period - javascript

I am calling axios.post with the url:
/constituents/941802/activities/rid/941802/rtype/Constituent/to/2021-10-01/type/Vol%2E%20Time?format=json
But it sends
/constituents/941802/activities/rid/941802/rtype/Constituent/to/2021-10-01/type/Vol.%20Time?format=json
How do I prevent this?
Using Axios 0.21.1
I have seen the suggestion of adding a trailing '/' at the end of the path, but that does not prevent the conversion and the server still finds the format to be illegal.
Sample:
post(url) {
return axios.post(
url,
{},
{responseType: 'json', headers: { 'Content-Encoding': 'gzip' }}
)
}

Related

Exporting formData from React to Spring boot backend

React code for build jsonBlob object
function jsonBlob(obj) {
return new Blob([JSON.stringify(obj)], {
type: "application/json",
});
}
exportFTP = () => {
const formData = new FormData();
formData.append("file", jsonBlob(this.state.ipData));
alert("Logs export to FTP server")
axios({
method: "post",
url: "http://localhost:8080/api/auth/uploadfiles",
data: formData,
headers: {
Accept: "application/json ,text/plain, */*",
"Content-Type": "multipart/form-data",
},
});
};
Spring boot backend that accepts for frontend request
public class UploadFile {
#Autowired
private FTPClient con;
#PostMapping("/api/auth/uploadfiles")
public String handleFileUpload(#RequestParam("file") MultipartFile file) {
try {
boolean result = con.storeFile(file.getOriginalFilename(), file.getInputStream());
System.out.println(result);
} catch (Exception e) {
System.out.println("File store failed");
}
return "redirect:/";
}
I want to figure out when I called the function from the frontend it's working properly but I change the state its doesn't send the object to the backend while the file appears in the directory. if I delete the file then only send it again and save it on the directory.
How I save multiple files while doesn't delete the previous ones
Thank you very much for your time and effort.
"Content-Type": "multipart/form-data",
Don't set the Content-Type yourself when posting a FormData.
The Content-Type needs to contain the boundary value that's generated by a FormData(example: multipart/form-data; boundary=----WebKitFormBoundaryzCZHB3yKO1NSWzsn).
It will automatically be inserted when posting a FormData instance, so leave this header out.
When you append blobs to a formdata then it will default the filename to just "blob"
On the backend you seems to override the file all the time:
con.storeFile(file.getOriginalFilename(), file.getInputStream());
Generate a new unik name if you want to keep all files
of topic but why not go with the fetch api? Smaller footprint. don't require a hole library...
fetch('http://localhost:8080/api/auth/uploadfiles', {
method: 'POST',
body: formData,
headers: {
Accept: 'application/json ,text/plain, */*'
}
})
In React application I used props to pass the file name from a different state and make sure to remove,
"Content-Type": "multipart/form-data",
Main function in React,
exportFTP = ({props from different state}) => {
const formData = new FormData();
formData.append("file", jsonBlob(this.state.ipData),{You can use this parm for pass name});
alert("Logs export to FTP server")
axios({
method: "post",
url: "http://localhost:8080/api/auth/uploadfiles",
data: formData,
headers: {
Accept: "application/json ,text/plain, */*"
},
});
};
And back end code I used same to get the original name then Its appears with the right name.
con.storeFile(file.getOriginalFilename(), file.getInputStream());
Chears !!

Using HTTP in NativeScript to send Post-data to a TYPO3-Webservice

I'm trying to send form data from a NativeScript app to a TYPO3-Webservice.
This is the JavaScript I'm using:
httpModule.request({
url: "https://my.domain.tld/webservice?action=login",
method: "POST",
headers: { "Content-Type": "application/json" },
content: JSON.stringify({
username:username,
password:password
})
}).then((response) => {
console.log("got response");
console.log(response.content);
//result = response.content.toJSON();
callback(response.content.toJSON());
}, (e) => {
console.log("error");
console.log(e);
});
But I can't read this data in the controller. Even with this:
$rest_json = file_get_contents("php://input");
$postvars = json_decode($rest_json, true);
$postvars is empty. $_POST is empty, too (which is - according to some docs - because the data is sent as JSON and thus the $_POST-Array isn't populated.
Whatever I do, whatever I try, I can't get those variables into my controller.
I tried it with fetch as well as with formData instead of JSON.stringify, same result.
I might have to add, that when I add the PHP-part in the index.php of TYPO3, $postvars is being populated. So I guess something goes missing, until the controller is called.
Any ideas?
the nativescript part seems ok, your problem must be corrected in the server side.
i use similare call and its works
// send POST request
httpModule.request({
method: "POST",
url: appSettings.getString("SERVER") + '/product/list',
content: JSON.stringify(data),
headers: {"Content-Type": "application/json"},
timeout: 5000,
}).then(response => { // handle replay
const responseAsJson = response.content.toJSON();
console.log('dispatchAsync\n\tresponse:', responseAsJson);
}, reason => {
console.error(`[ERROR] httpModule, msg: ${reason.message}`);
});

Error sending Content_Tags while posting a video using FB API

I have tried many different ways but to no avail
API Spec - https://developers.facebook.com/docs/graph-api/reference/page/videos/
Param - content_tags ( list ) --> is what required
Below is my form data that is being posted
const formData = {
file_url: postOptions.filepath,
title: postOptions.title,
description: postOptions.description,
content_tags: ['tags', 'hello', 'hi']
};
HTTP Request Options
const options = {
url: https://graph-video.facebook.com/v9.0/${pageId}/videos?access_token=${accessToken},
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
},
formData,
};
Error response returned.
{"error":
{
"message":"(#100) Param content_tags[0] must be a valid ID string (e.g., \"123\")",
"type":"OAuthException",
"code":100,
"fbtrace_id":"ANoCbTSnh4uL960SjyE6XBV"
}
}
As per documentation, seems it has to be not just any string but NUMBER string which are predefined IDs of the tag list<numeric string>
From documentation
Tags that describe the contents of the video. Use search endpoint with type=adinterest to get possible IDs.
Example:
~~~~
/search?type=adinterest&q=couscous
~~~~
Here's full path of the above example shown by facebook, how you can get some IDs:
https://graph.facebook.com/search?type=adinterest&q=​"home"&limit =10&access_token={{access_token}}

JS: axios POST with large nested object and form-data

I am to post an Axios request because using get results in a 414 error.
Here's the object:
rows= {
0 : {
"name":"Thor",
"status":"active",
"email":"somuchlightning#kaboom.io",
},
1 : {
"name":"Mesa",
"status":"active",
"email":"big-mesa#tundra.com",
},
2 : {
"name":"Jesper",
"status":"stdby",
"email":"jes#slap.net,
},
}
This is just a sample of the object's format. There is 400+ elements in the real one, thus post instead of get. I am having trouble properly building the form-data on this one. Here's what I have:
let data = new FormData();
Object.keys(rows).forEach(key => data.append(key, rows[key])); // <--- this doesn't do
data.set('target', target); // <---- this comes through just fine
axios({
method: 'post',
url: 'byGrabthorsHammer.php',
data: data,
headers: {'Content-Type': 'multipart/form-data'}
}).then(function(response) {
if (response.error) {
console.log('failed to send list to target');
console.log(response);
} else {
console.log('response: ');
console.log(response);
}
});
What comes through is just [Object][Object]' when ivar_dump($_POST);`. This is not what I want. How could I rewrite this properly so I get the data to the other side (like GET...).
Yow bro, POST Are for inserting new stuff, instead of doing a post you need a patch
axios.patch it is basically the same. And it won’t fix your issue.
To fix the issue you need to set the Content-Type to application/json, then on yow
axios.post(url, data: JSON.stringify(bigObject))
.then(Rea=>Rea)
You could try stringifying the data. JSON.stringify(data)

How to disable caching on get call?

I would like to disable cache on getting a request in vue environment. I already tried this but it does not work.
api.js (file)
getCall: () => {
return performAsyncGet(apiConfig.getCall.url,
requestConfigJSON, _REQUEST_TOKENS.getCall, apiConfig.getCall.cache)
.then(
response => response.data
);
},
(apiConfig.js) (file)
getCall: {
url: `${servicePathPrefixOrDomain}/api/getCall`
cache: false
}
Does anybody know how to disable the cache, when making a get request in vue.js?
Thanks in advance!
To avoid caching you can make your url unique by appending timestamp as a querystring parameter like this:
getCall: {
url: `${servicePathPrefixOrDomain}/api/getCall?_t={new Date().getTime()}`
cache: false
}
In this way for every ajax call the url will be unique due to different timestamp and browser will not cache the response.
Is solved adding the next code in the header:
const requestConfigJSON = {
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache'
}
};

Categories