I'm building a react native app post requesting laravel php api. it works on postman but not on Axios. Do you know how can i solve? I can't post a form data
I tried other forms sending post request of Axios. but none of them is solution
axios({
method: 'post',
url: 'URL',
params: {
"api_token": token,
"name": "talha"
},
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data'
}
}).then(response => alert(response)).catch(err => console.warn(err))
-----
const serverURL = "URL";
const http = axios.create({
timeout: 1000,
baseURL: serverURL,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
withCredentials: false,
cache: false,
dataType: "jsonp"
});
data is a formdata
await http.post("/passengers", data, config)
.then(Response => alert(Response.data))
.catch(error => console.warn("hata", error))
-----
axios.post( 'URL',
data,
{
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data'
}
}
).then(function(){
alert('SUCCESS!!');
})
.catch(function(){
alert('FAILURE!!');
});
postman script:
https://pastebin.ubuntu.com/p/vS54dytpCQ/
You can use my API helper function for batter development.
import axios from 'axios';
import AsyncStorage from '#react-native-community/async-storage';
const api = async (url, method, body) => {
/**
* config object for fetch
*/
const config = {
method: 'get',
baseURL: 'BASEURL WILL BE HERE',
url,
headers: {
'Content-type': 'application/json',
authorization: await AsyncStorage.getItem('auth_token'),
},
};
if (method) {
config.method = method;
}
if (body) {
config.data = body;
}
let response;
try {
response = await axios(config);
return {...response.data};
} catch (e) {
throw new Error(e.message);
}
};
export default api;
Then use this function
import api from 'filpath';
const functionName = async () => {
try{
const res = await api('/passengers', 'POST' posData);
console.log(res.data);
} catch(e){
alert('FAILURE!!')
}
}
Note: Save the auth token to AsyncStorage when user login.
Related
I'm doing a login with laravel/sanctum and sveltekit, when I submit the form,first inside the actions I execute first a fetch to the csfr endpoint from sanctum ('/sanctum/csrf-cookie') but in the reponse the cookies are not set automatically in the browser but cookies arrive.So how i can set automatically?
Here the code :
`export const actions: Actions = {
default: async ({ request, fetch, cookies }) => {
const formData = await request.formData();
const user = {
name: formData.get('name'),
email: formData.get('email'),
password: formData.get('password'),
password_confirmation: formData.get('password_confirm')
};
await fetch('http://localhost:8000/sanctum/csrf-cookie', {
method: 'GET',
credentials: 'include'
});
const res = await fetch('http://127.0.0.1:8000/api/register', {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json'
// 'X-XSRF-TOKEN': '' || ''
},
body: JSON.stringify(user)
});
const data = await res.json();
console.log(data);
}
};`
I am writing API tests using Cypress 6.4.0 & TypeScript where I need to upload a pdf file in the request body.
My code for the request is:
My code for the request body is:
public async createAssetDocTest() {
let url = sharedData.createAsset_url + sharedData.assetA;
let response = await fetch(url
,
{
method: 'POST',
body: await requestbody.createAssetDocBody(),
headers: {
Authorization: sharedData.bearer + " " + adminTokenValue,
Accept: sharedData.accept,
'Content-type': sharedData.docReqContent,
},
}
);
expect(response.status).to.equal(200);
public async createAssetDocBody(): Promise<any> {
const file = sharedData.doc;
cy.fixture(file).then((pdfDoc) => {
Cypress.Blob.binaryStringToBlob(
pdfDoc,
sharedData.contentTypeValue
).then(async (blob: string | Blob) => {
const formData = new FormData();
formData.set(sharedData.document, blob, file);
const body = {
formdata: {
document: {
value: pdfDoc,
options: {
filename: sharedData.document,
contentType: null,
},
},
},
};
return body;
});
});
}
However, the file does not upload the file & the request fails with error 400. Is there a better way to upload files in the body of the POST request?
enter image description here
Resolved this issue!
The main issue was that my Cypress version was too old. Upgraded to 9.7.0
Then added the following code:
public async createAssetDoc(): Promise<any> {
cy.fixture("pic location", "binary")
.then((file) => Cypress.Blob.binaryStringToBlob(file))
.then((blob) => {
var formdata = new FormData();
formdata.append("document", blob, "pic location");
const url = "your url";
cy.request({
url,
method: "POST",
body: formdata,
headers: {
Authorization:
"bearer" + " " + token,
Accept: "application/json",
"Content-Type": "multipart/form-data",
},
}).then((response) => {
expect(response.status).to.equal(201);
expect(response.statusText).to.equal(
sharedData.fileUploadStatusText
);
const finalResponse = String.fromCharCode.apply(
null,
new Uint8Array(response.body)
);
return finalResponse;
});
});
}
I've looked at some of the other posts on this and it seems I need to apply 'await' I'm just not sure how to modify the following to do that
function sendData(url,emailPass){
let bodyFormData = new FormData()
for (const [key, value] of Object.entries(emailPass)) {
console.log(key,value)
bodyFormData.append(key,value)
}
axios({
method: 'POST',
url: url,
data: bodyFormData,
headers: {'Content-Type': 'multipart/form-data'}
})
.then(function (response){
return response.data
})
.catch(function(response){
return response
})
}
You should modify the function to return the promise from axios, which returns the response data.
function sendData(url,emailPass){
let bodyFormData = new FormData()
for (const [key, value] of Object.entries(emailPass)) {
console.log(key,value)
bodyFormData.append(key,value)
}
return axios({
method: 'POST',
url: url,
data: bodyFormData,
headers: {'Content-Type': 'multipart/form-data'}
})
.then(function (response){
return response.data
})
.catch(function(response){
return response
})
}
If you want to use async/await you can do
async function sendData(url,emailPass){
let bodyFormData = new FormData()
for (const [key, value] of Object.entries(emailPass)) {
console.log(key,value)
bodyFormData.append(key,value)
}
try{
const response = await axios({
method: 'POST',
url: url,
data: bodyFormData,
headers: {'Content-Type': 'multipart/form-data'}
});
return response.data;
}catch(e){
return e.response.data;
}
}
webpage; videochat.js; room.js
const handleSubmit = useCallback(async event => {
event.preventDefault();
alert('Work');
const data = await fetch('./video/token', {
method: 'POST',
body: JSON.stringify({
identity: username,
// room: roomName
}),
headers: {
'Content-Type': 'application/json'
}
}).then(res => res.json());
setToken(data.token);
}, [username, roomName]);
This is the part where I am likely having an issue (lines 18-32 of videochat.js)
I would like to use Cypress for API testing. My goal is to extract a part of the API response and pass it to another API request. Here's a sample code:
Cypress.Commands.add('createCustomer', () => {
return cy.request({
method: 'POST',
url: 'api/v1/Customers',
headers: {
'Content-Type': 'application/json'
},
body: {
// sample content
}
}).then((response) => {
return new Promise(resolve => {
expect(response).property('status').to.equal(201)
expect(response.body).property('id').to.not.be.oneOf([null, ""])
const jsonData = response.body;
const memberId = jsonData.id
resolve(memberId)
return memberId
})
})
})
With this code, I am getting [object%20Object] as the result.
Hoping for some feedback.
So you are adding the id generated by the POST to a subsequent GET request?
Try returning the id without using a Promise, I don't think you need one at that point since the response has already arrived.
}).then((response) => {
expect(response).property('status').to.equal(201)
expect(response.body).property('id').to.not.be.oneOf([null, ""])
const jsonData = response.body;
const memberId = jsonData.id;
return memberId;
})
Url for GET
cy.createCustomer().then(id => {
const url = `api/v1/Customers${id}`;
...
or
cy.createCustomer().then($id => {
const id = $id[0]; // Not quite sure of the format, you may need to "unwrap" it
const url = `api/v1/Customers${id}`;
...
If you want to pass response from API Request 1 to API Request 2, you can do something like this:
describe('Example to demonstrate API Chaining in Cypress', function () {
it('Chain two API requests and validate the response', () => {
//Part 1
cy.request({
method: 'GET',
url: 'https://www.metaweather.com/api/location/search/?query=sn',
}).then((response) => {
const location = response.body[0].title
return location
})
//Part 2
.then((location) => {
cy.request({
method: 'GET',
url: 'https://www.metaweather.com/api/location/search/?query=' + location
}).then((response) => {
expect(response.status).to.eq(200)
expect(response.body[0]).to.have.property('title', location)
})
})
})
})
Your code seems to be failing during the initial request, not during the subsequent actions. I am far from a Javascript expert, but you seem to have some unnecessary complexity in there. Try simplifying your command like this and see if you can at least get a successful request to go through:
Cypress.Commands.add('createCustomer', () => {
cy.request({
method: 'POST',
url: 'api/v1/Customers',
headers: {
'Content-Type': 'application/json'
},
body: {
// sample content
}
})
})
And if that works, keep going:
Cypress.Commands.add('createCustomer', () => {
cy.request({
method: 'POST',
url: 'api/v1/Customers',
headers: {
'Content-Type': 'application/json'
},
body: {
// sample content
}
}).then((response) => {
expect(response).property('status').to.equal(201)
expect(response.body).property('id').to.not.be.oneOf([null, ""])
const jsonData = response.body;
const memberId = jsonData.id
return memberId
})
})