Rewrite jquery ajax request in axios and set xhrFields - vue.js

i HAVE jquery request
$.ajax({
type: "GET",
url: "http://6232423.212342343.100.89:9000/api/v2/content/categories/",
xhrFields: {
withCredentials: true
},
});
how do I make the same but in axios?
I tried like this:
axios.get(portal.categoriesUrl,
{xhrFields: {
withCredentials: true
}}
)
but didn't work

axios.get(url, { withCredentials: true })
see docs
https://github.com/mzabriskie/axios

Related

Calling the auth function will call the wrong url

I'm using the Nuxt/Auth library in a NuxtJs project. I'm trying to make a login request to my backend. So I don't use any of the existing schemes that the library has prepared by default.
This is what my configuration looks like in nuxt.config.js
axios: {
baseUrl: 'https://api.release.my-custom-domain.com',
credentials: true,
proxy: true
},
proxy: {
'/api/': {
target: 'https://api.release.my-custom-domain.com',
pathRewrite: {'^/api/': ''}
}
},
auth: {
strategies: {
local: {
token: {
property: 'token',
global: true,
},
user: {
property: 'user'
},
endpoint: {
login: {url: '/api/v1/auth', method: 'post', propertyName: false}
}
}
}
},
I use a proxy because of a problem with cors.
This is what my code looks like in vue.
methods: {
async loginFormSubmit () {
try {
let response = await this.$auth.loginWith('local', { data: this.login })
console.log(response);
} catch (err) {
console.log(err);
}
}
}
After I call the function, the XRH request runs, but it always adds /login to the url request.
This is what the url should look like - http://localhost:3000/api/auth
But the request looks like this - http://localhost:3000/api/auth/login
Didn't someone already solve this problem?
Thank you for your answers.

Default content-type does not replace with new content-type (form-data) in axios in react native app for uploading image

I want to upload an image with axios in react native. This is my function which call upload image web service api:
function _uploadImgToServer(item) {
const file = {
uri: item.imgData.path,
type: item.imgData.mime,
name: 'ana' + item.imgId
}
const body = new FormData();
body.append('file', file);
console.log('uploadResult saga0', body)
dispatch(uploadImg({ body: JSON.stringify(body)}))
}
this is my axios config:
const instance = axios.create({
baseURL: '****',
responseType: 'json',
timeout: 10000,
headers: {
'WEB_TOKEN': '*****',
'UNIQUE_ID': '*****',
'UNIQUE_KEY': '*****',
Accept: "application/json",
'Content-Type': "multipart/form-data"
},
});
And I call my web service like bellow:
try {
const response = await instance.post(url, data);
return Promise.resolve(response.data);
} catch (error) {
return Promise.reject(error.response);
}
Part of the response I get in last part is:
'My log result' { data: { Code: 3, Message: 'Invalid Entry', Value: null },
status: 200,
statusText: undefined,
headers:
{
...
'content-type': 'application/json; charset=utf-8',
...
},
config:
{ url: 'upload',
method: 'post',
data: '{"_parts":[[{"uri":"file:///data/data/***packageName***/cache/react-native-image-crop-picker/IMG-20201222-WA0017.jpg","type":"image/jpeg","name":"ana_pu8kweg4e"},null]]}',
headers:
{ Accept: 'application/json',
'Content-Type': 'multipart/form-data',
WEB_TOKEN: '*****',
UNIQUE_ID: '****',
UNIQUE_KEY: '****' },
baseURL: '****',
transformRequest: [ [Function: transformRequest] ],
transformResponse: [ [Function: transformResponse] ],
timeout: 10000,
adapter: [Function: xhrAdapter],
responseType: 'json',
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
validateStatus: [Function: validateStatus] },
...
}
As you see in my log result, the content-type in header I have sent is 'multipart/form-data' but server has received 'application/json; charset=utf-8' so I cannot upload my image.
It is worth to mention that if I do not use JSON.stringify, content-type will not be sent at all. I have searched a lot but I could not find any useful response.
I found that my problem was not about "content-type" at all. I had to put image type at the end of the image name.
const file = {
uri: item.imgData.path,
type: item.imgData.mime,
name: 'ana'+item.imgId+'.jpeg'
}
I've just added '.jpeg' at the end of the name. I think it is depended on the backend programmer coding algorithm and It cannot cause problem always.

upload expo camera roll image to server

I'm using expo camera to take a picture. The output I get is a file in format file:///data/user/0/host.exp.exponent/..../Camera/1075d7ef-f88b-4252-ad64-e73238599e94.jpg
I send this file path to the following action and try to upload it to
export const uploadUserPhoto = (localUri,uid) => async dispatch => {
let formData = new FormData();
formData.append('avatar', { uri: localUri, fileName: uid});
let res = await fetch(`${API_URL}api/uploadPhoto`, {
method: 'POST',
body: formData,
header: {
'content-type': 'multipart/form-data',
},
});
Afterward, I get [Unhandled promise rejection: TypeError: Network request failed] and nothing arrives to server. I tried using some string to send in the body and the fetch worked, so I guess it has something to do with my formData configuration.
The formData is:
{
"_parts": Array [
Array [
"avatar",
Object {
"fileName": "6eAntcmoEsdBeSD2zfka9Nx9UHJ3",
"type": "jpg",
"uri": "file:///data/us....2e6e3e8d3223.jpg",
},
],
],
}
How I use postman to test my sails controller
Sails controller function:
uploadPhoto: function (req, res) {
req.file('avatar').upload({
adapter: require('skipper-s3'),
key: 'XXXX',
secret: 'XXX',
bucket: 'XXX',
saveAs: req.param('fileName') + '.png',
}, function (err, filesUploaded) {
....
});
});
}
Problem was that I didn't specify the filename.
Just did this and it worked!!! :)
data.append('filename', 'avatar');
data.append('fileName', uid);
data.append('avatar', {
uri: photo.uri,
name: 'selfie.jpg',
type: 'image/jpg'
});
const config = {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
body: data
};
fetch(`${API_URL}api/uploadPhoto`, config).then(responseData => {
console.log(responseData);
}).catch(err => { console.log(err); });
just add these params in photo this worked for me
data.append('avatar', {
uri: photo.uri,
name: 'selfie.jpg',
type: 'image/jpg'
});

protractor GET and PUT API call

I want to do API call in my protractor test case inside beforeAll() function and once I get the promise return my Test cases should start running. as my test cases are heavily dependent on API response.
I tried using jQuery however it is showing 'jQuery is undefined.' I am using protractor5.3.0.
var data ={
"request": {
"urlPattern": "/portal/user/profile",
"method": "GET",
"headers": {
"Accept": {
"contains": "application/json"
},
"Content-Type": {
"contains": "application/json"
}
}
},
"response": {
"bodyFileName": "abc.json",
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Headers": "Content-Type",
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Origin": "{{request.headers.Origin}}"
},
"transformers": [
"response-template"
]
}
};
function setUserProfile(profile, data){
var id;
if(data) {
data.response.bodyFileName = "abc.json";
}
jQuery.ajax({
url: "someurl",
type: 'GET',
dataType: 'json',
contentType: 'application/json',
success: function(result) {
result.mappings.forEach(function(mappingItem) {
if(mappingItem.request.urlPattern === '/portal/user/profile') {
id = mappingItem.id;
}
});
jQuery.ajax({
url: "someurl",
type: 'PUT',
data: JSON.stringify(data),
dataType: 'json',
contentType: 'application/json',
success: function(result) {
console.log("success?", result);
}
});
}
});
}
describe('Logout Page', function () {
var userDropdownEle;
beforeAll(function () {
request('someurl', function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML for the Google homepage.
});
userDropdownEle = element(by.css(logoutSelectors.dropDownButton));
xchangePageObject.getLoginUrl();
});
});

html page .net connection using web services error

$.ajax({
cache: false,
type: "GET",
url: "http://localhost:49326/WebSite1/Service.asmx/calledfunction",
data:{},
contentType: 'application/json',
dataType: "jsonp",
jsonp : "callback",
jsonp: "jsonpcallback",
crossDomain: true,
success: function (result)
{
alert(result);
}
});
i was getting this error
jquery3.2.1.min.js:4GET:http://localhost:49326/WebSite1/Service.asmx/calledfunction?callback=jQuery32103652224465323135_1501578805141&_=1501578805143