Why is response undefined in Fetch request using Redux Store - post

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.

Related

HTTP request is returns 400, but cannot throw error

Trying to use this request post function. When I run it with the correct requestBody it works fine, but if the requestBody is invalid it returns a HTTP 400 and fails, but no matter what I try to throw, or as such, the catch block never runs. Can anyone help? This is in Node and using the request package.
const res = async() =>
{
try
{
const res = await request({
method: "POST",
url: "url",
headers: {
"content-type": "application/json",
"authorization": "Basic " + Buffer.from(username + ":" + password).toString("base64")
},
body: JSON.stringify(requestBody)
}, function(error, response, data)
{
if(response.statusCode == 201 || response.statusCode == 200)
{
console.log(data);
}
else
{
console.log("Fell into else block!");
throw new Error("POST failed!");
}
});
}
catch (error)
{
console.log("something went wrong!", error);
}
};
Since request function returns a promise use catch method
const res = await request({
method: "POST",
url: "url",
headers: {
"content-type": "application/json",
"authorization": "Basic " + Buffer.from(username + ":" + password).toString("base64")
},
body: JSON.stringify(requestBody)
}, function(error, response, data)
{
if(response.statusCode == 201 || response.statusCode == 200)
{
console.log(data);
}
else
{
console.log("Fell into else block!");
throw new Error("POST failed!");
}
})
.catch((error) => {
console.log("something went wrong!", error);
});

NativeScript-Angular - POST formdata to Wordpress ContactForm7 API

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);
});
}

Response Isn't Converting To JSON

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'))
}

Uploading video to server

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;

Service Worker w offline.html Backup Page

I can't get the offline.html page to display. I keep getting the The FetchEvent for "https://my-domain.com" resulted in a network error response: a redirected response was used for a request whose redirect mode is not "follow".
Here's the snippet of my service-worker.js which should return the offline.html when the network is unavailable.
self.addEventListener('fetch', function(event) {
if (event.request.mode === 'navigate' || (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
if(event.request.url.includes("my-domain.com")){
console.log(event.request);
event.respondWith(
caches.match(event.request).then(function(resp) {
return resp || fetch(event.request).then(function(response) {
let responseClone = response.clone();
caches.open(CACHE_NAME).then(function(cache) {
cache.put(event.request, responseClone);
});
return response;
});
}).catch(function() {
return caches.match("/offline.html");
})
);
}
}
});
Below is the console.log of my network request (page refresh when offline)
Request {method: "GET", url: "https://my-domain.com", headers: Headers, destination: "unknown", referrer: "", …}
bodyUsed:false
cache:"no-cache"
credentials:"include"
destination:"unknown"
headers:Headers {}
integrity:""
keepalive:false
method:"GET"
mode:"navigate"
redirect:"manual"
referrer:""
referrerPolicy:"no-referrer-when-downgrade"
signal:AbortSignal {aborted: false, onabort: null}
url:"https://my-domain.com"
__proto__:Request
I got this working / found the fix. It was related to a redirected response security issue in the browser. From the Chromium Bugs Blog, Response.redirected and a new security restriction.
Solution: To avoid this failure, you have 2 options.
You can either change the install event handler to store the response generated from res.body:
self.oninstall = evt => {
evt.waitUntil(
caches.open('cache_name')
.then(cache => {
return fetch('/')
.then(response => cache.put('/', new Response(response.body));
}));
};
Or change both handlers to store the non-redirected response by setting redirect mode to ‘manual’:
self.oninstall = function (evt) {
evt.waitUntil(caches.open('cache_name').then(function (cache) {
return Promise.all(['/', '/index.html'].map(function (url) {
return fetch(new Request(url, { redirect: 'manual' })).then(function (res) {
return cache.put(url, res);
});
}));
}));
};
self.onfetch = function (evt) {
var url = new URL(evt.request.url);
if (url.pathname != '/' && url.pathname != '/index.html') return;
evt.respondWith(caches.match(evt.request, { cacheName: 'cache_name' }));
};

Resources