Hello everyone and thanks in advance ...
I'm trying to use the Contact Form7 APIs to fill in and submit a form from an Angular NativeScript App.
I have tried different solutions but I always get the same error response.
{"into":"#","status":"validation_failed","message":"Oops, there seems to be some error in the fields. Check and try again, please.","invalidFields":[{"into":"span.wpcf7-form-control-wrap.nome","message":"Attention, this field is required!","idref":null},{"into":"span.wpcf7-form-control-wrap.mail","message":"Attention, this field is required!","idref":null}]}
In the example I have entered static values in the body for convenience
Help me ;(
attempt 1
onTappedInvia(): void {
fetch("http://www.example.com/wp-json/contact-form-7/v1/contact-forms/{id}/feedback", {
method: "POST",
headers: { "Content-Type": "multipart/form-data" },
body: JSON.stringify({
nome: "Test API",
mail: "test#test.test"
})
}).then((r) => r.json())
.then((response) => {
const result = response.json;
console.log(response);
}).catch((e) => {
console.log(e);
});
}
attempt 2
deliverForm() {
var formData: any = new FormData();
formData.append('nome', "Test API");
formData.append('email', "test#test.test");
formData.append('your-message', "Test API");
this.submitted=true;
console.log(formData);
this.formService.create(formData)
.subscribe(
data => {
console.log('Invoice successfully uploaded');
console.log('Error'+ JSON.stringify(data));
},
error => {
console.log('Error'+ JSON.stringify(error));
});
console.log('USCITO');
}
and formService
const HttpUploadOptions = {
headers: new HttpHeaders({ "Content-Type": "multipart/form-data;" })
}
#Injectable({
providedIn: 'root'
})
export class FormService {
constructor(
private HttpClient: HttpClient
) { }
create(formData){
return this.HttpClient.post('http://www.example.com/wp-json/contact-form-7/v1/contact-forms/{id}/feedback', formData, HttpUploadOptions)
}
}
The problem was with the Content-Type. i tried with application/x-www-form-urlencoded and it works!
fetch("http:www.aficfestival.it/wp-json/contact-form-7/v1/contact-forms/5173/feedback?", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: form
}).then((r) => r.json())
.then((response) => {
const result = response.json;
console.log(response);
}).catch((e) => {
console.log(e);
});
}
Related
first way I tried is :
static async callSendApi(requestBody) {
let url = new URL(
`${API_URL}/${PAGE_ID}/messages`
);
url.search = new URLSearchParams({
access_token: `${PAGE_ACCESS_TOKEN}`,
});
console.warn("Request body is\n" + JSON.stringify(requestBody));
let response = await axios.post(url, {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(requestBody),
// access_token: `${PAGE_ACCESS_TOKEN}`,
});
if (!response.ok) {
consoleconst`Unable to call Send API: ${response.statusText}`,
await response.json();
}
}
Second way I tried is :
static async callSendApi(requestBody) {
let url = new URL(
`${API_URL}/${PAGE_ID}/messages?access_token=${PAGE_ACCESS_TOKEN}`
);
/* url.search = new URLSearchParams({
access_token: `${PAGE_ACCESS_TOKEN}`,
});*/
console.warn("Request body is\n" + JSON.stringify(requestBody));
let response = await axios.post(url, {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(requestBody),
// access_token: `${PAGE_ACCESS_TOKEN}`,
});
if (!response.ok) {
consoleconst`Unable to call Send API: ${response.statusText}`,
await response.json();
}
}
the error I get :
error: {
message: 'Unknown path components: /messagesaccess_token=access_token
type: 'OAuthException',
code: 2500,
fbtrace_id: 'AbBJGVotjz3ijKKLzVE6_CM'
}
I'm receiving this error in both ways. both ways are escaping the '?' mark. I have no idea what is happening.. I'm using heroku for this. I tried deleting and redeploying the repository to confirm if the code is not updating. but still gives this error. :( .
I tried withot using URL and URLSearchParams and it worked!
below is my code:
static async callSendApi(requestBody) {
console.warn("Request body is\n" + JSON.stringify(requestBody));
let response = await axios.post(
`${API_URL}/${PAGE_ID}/messages`,
{
params: { access_token: `${PAGE_ACCESS_TOKEN}` },
},
{
headers: { "Content-Type": "application/json" },
body: JSON.stringify(requestBody),
}
);
if (!response.ok) {
consoleconst`Unable to call Send API: ${response.statusText}`,
await response.json();
}
}
Hi I'm trying to POST image to Strapi via api/uploads with Axios
With code below I have reponse with code 200, but in Strapi UI get file with no image, but with other parameters.
Something like this
return bot.getFileLink(msg.photo[0].file_id).then((resp) => {
axios.get(resp, { responseType: 'buffer' }) // geting img from telegram link
.then(axres => {
const buffer = Buffer.from(axres.data) // make Buffer obj
const imgdata = new formdata()
imgdata.append('files', buffer, { filename: resp }) // append to FormData object
axios.post(`http://localhost:1337/api/upload`, imgdata, {
headers: { 'Content-Type': 'multipart/form-data' },
})
.then(response => {
console.log(response);
})
.catch(err => {
console.log(err);
})
})
})
In docs provided example with FormData in body option, but in this case I have error "Bad request 400"
await fetch('/api/upload', {
method: 'post',
body: new FormData(e.target)
});
Solved. With "binary" endocding in Buffer it works perfect.
return bot.getFileLink(msg.photo[0].file_id).then((resp) => {
axios.get(resp, { responseType: 'arraybuffer' })
.then(axres => {
const buffer = Buffer.from(axres.data, 'binary')
const imgdata = new formdata()
imgdata.append('files', buffer, { filename: resp })
console.log(buffer)
axios.post(`http://localhost:1337/api/upload`, imgdata, {
headers: { 'Content-Type': 'multipart/form-data' },
})
.then(response => {
console.log('ok');
})
.catch(err => {
console.log(err);
})
})
})
I'm trying to take info from a React form and post it to my Rails database, but I get an error "unexpected token '<' at position 0" which means my response is still HTML and not JSON.
Here's my code:
export const createCar = car => {
return dispatch => {
return fetch(`${API_URL}/cars/create`, {
method: "POST",
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({ car: car })
})
.then(response => response.json())
.then(car => {
dispatch(addCar(car))
dispatch(resetCarForm())
})
.catch(error => console.log(error + 'createCar POST failed'))
}
}
Is there a reason why it's not converting to JSON?
Additionally, I don't seem to be able to drop debugger into my code, or at least in this function - do I need to import it or something?
I'm thinking that your server is sending you back HTML and then you are trying to parse it in response.json()
use a try/catch in this block:
export const createCar = car => {
return dispatch => {
return fetch(`${API_URL}/cars/create`, {
method: "POST",
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({ car: car })
})
.then(response => {
try {
return response.json()
} catch(error) {
console.error(error);
}
})
.then(car => {
dispatch(addCar(car))
dispatch(resetCarForm())
})
.catch(error => console.log(error + 'createCar POST failed'))
}
I'm using react-native-camera(^0.6.0) in my app, I have to upload the recorded video to server as multipart data. In android they are posting like this,
{
_parts: [
[
'file',
{
name: 'VID_20181130_150959.mp4',
uri: 'file:///storage/emulated/0/DCIM/VID_20181130_150959.mp4',
type: 'video/mp4'
}
]
]
}
but in iOS the file path is returning as assets-library://asset/asset.mov?id=41B76A24-1018-46C1-A658-C1EFFC552FD0&ext=mov but if I post the assets path it's not uploading.
{
_parts: [
[
'file',
{
name: '41B76A24-1018-46C1-A658-C1EFFC552FD0.mov',
uri: 'assets-library://asset/asset.mov?id=41B76A24-1018-46C1-A658-C1EFFC552FD0.mov',
type: 'video/mov'
}
]
]
}
Can anyone help me out with this????
I'm using iPhone 6 for debugging the code,
var url = DomainAPI.lashHostname + '/attachments?token=' + value + '&class=Quick';
fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body: JSON.stringify(formData)
}).then((response) => response.json())
.then((responseData) => {
console.log('responseData------->************$$$$$$$$$$$' + JSON.stringify(responseData));
if (responseData.error.code == 0) {
this.sendFiletoServer(responseData.id, value);
} else {
this.setState({ loading: false });
Actions.pop();
}
}).catch((err) => {
console.log('responseData-------> err ************$$$$$$$$$$$' + JSON.stringify(err));
this.setState({ loading: false });
Actions.pop();
});
See This code worked for me hope it helps
let formData = new FormData();
formData.append("videoFile", {
name: name.mp4,
uri: video.uri,
type: 'video/mp4'
});
formData.append("id", "1234567");
try {
let response = await fetch(url, {
method: 'post',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formData
});
return await response.json();
}
catch (error) {
console.log('error : ' + error);
return error;
I am writing a Fetch request to post new users to an application. The fetch is integrated with a redux store. Response returns [object Object] and response.status returns undefined. I am new to Redux and am wondering if that is where the error is. Here is the code from my actions creator file:
export function createCustomerSuccess(values) {
return {
type: types.CREATE_CUSTOMER_SUCCESS,
values: values
};
}
export function createCustomer(values) {
return function (dispatch, getState) {
console.log('values passing to store', values);
return postIndividual(values).then( (response) => {
console.log('calling customer actions');
console.log(response);
if(response.status === 200){
console.log(response.status);
dispatch(createCustomerSuccess(values));
console.log('create customer success');
}
else {
console.log('not successful');
}
});
};
}
function postIndividual(values) {
console.log('test from post' + JSON.stringify(values));
const URLPOST = "http://myurlisworking/Add";
return fetch (URLPOST, {
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
"Access-Control-Origin": "*"
},
body: JSON.stringify(values)
})
.then(response => response.json())
.then(response => {
console.log('response' + response.status)
});
}
Issue seems like with your fetch expectations. When your first .then gets called after fetch() then you get response.status available there to check.
You can rewrite your fetch like below and see if that resolves.
function postIndividual(values) {
console.log('test from post' + JSON.stringify(values));
const URLPOST = "http://myurlisworking/Add";
return fetch (URLPOST, {
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
"Access-Control-Origin": "*"
},
body: JSON.stringify(values)
})
.then(response => {
console.log('response' + response.status)
return response.ok && response.json();
})
.catch(err => console.log('Error:', err));
}
You can check response.status here ^ and do what you want.
Alternatively you can just do the fetch in postIndividual and handle response in your createCustomer instead.