Cannot consume rest api (Web Api) from component React - asp.net-mvc

I'm developing a web, it consume a rest api, this api rest is build in asp.net as a Web Api. My issue is present when try consume an endpoint, because use fetch, but this not show any.
this is my code
import React from 'react';
import BootstrapTable from 'react-bootstrap-table-next';
class BundleShipping extends React.Component {
constructor(props) {
super(props)
this.state = {
pickTicket: '',
Pallets: [],
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({ pickTicket: event.target.value });
}
handleSubmit(event) {
this.GetParametersPickTicket('016683O01', 'en-US', 'e3eda398-4f2a-491f-8c8e-e88f3e369a5c')
.then((responseData) => { this.setState({ Pallet: responseData.Data.Pallet }) })
.then((response) => console.log(response))
}
GetParametersPickTicket(PickTicket, language, Plant) {
console.log(PickTicket)
console.log(language)
console.log(Plant)
return fetch('http://localhost:55805/api/GicoBundleWA/GetParametersPickTicket', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
pickTicket_str: PickTicket,
kPlant: Plant,
language: language
}),
}).then((response) => response.json())
.then((responseJson) => { console.log(JSON.stringify(responseJson)) })
.catch((err) => console.log(err))
}
render() {
const columns = [{
dataField: 'PalletNumber',
text: 'Estibas Cargadas'
}, {
dataField: 'Quantity',
text: 'Cantidad'
}, {
dataField: 'Bundles',
text: 'Bultos'
}, {
dataField: 'Date_Time',
text: 'Fecha de carga'
}];
return (
<div className="container">
<form onSubmit={this.handleSubmit}>
<div className="col-lg-2 col-md-2 col-xs-3">
<label>Shipping</label>
</div>
<div className="form-group col-lg-5 col-md-5 col-xs-5">
<input type="text" value={this.state.pickTicket} onChange={this.handleChange} className="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter Pick Ticket" />
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
<BootstrapTable keyField='PalletNumber' data={this.state.Pallets} columns={columns} />
</div>
)
}
}
but onclick in the button not show data in console, only show it
016683O01 VM494 bundle.js:67423
en-US VM494 bundle.js:67424
e3eda398-4f2a-491f-8c8e-e88f3e369a5c VM494 bundle.js:67425
Navigated to http://localhost:3000/xxxx?
react-dom.development.js:17286 Download the React DevTools for a better development experience:
I did some tests for discover my error, for example execute code directly in console so:
function GetParametersPickTicket(PickTicket, language, Plant) {
console.log(PickTicket)
console.log(language)
console.log(Plant)
return fetch('http://localhost:xxx/api/XXX/YYYY', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
pickTicket_str: PickTicket,
kPlant: Plant,
language: language
}),
}).then((response) => response.json())
.then((responseJson) => { console.log(JSON.stringify(responseJson)) })
.catch((err) => console.log(err))
}
GetParametersPickTicket('016683O01', 'en-US', 'e3eda398-4f2a-491f-8c8e-e88f3e369a5c')
and this one if it shows my answer json.
Additionally, i resolved issue with cors, and try with postman and it show
access-control-allow-origin β†’*
I don't understand, why in component react does not show any result

First problem is that your method GetParametersPickTicket simply logs the received json, but it never returns it. So, the consumer of this method will simply receive an empty resolved promise. See my comment "This part was missing" in the following snippet:
GetParametersPickTicket(PickTicket, language, Plant) {
return fetch('http://localhost:55805/api/GicoBundleWA/GetParametersPickTicket', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
pickTicket_str: PickTicket,
kPlant: Plant,
language: language
}),
}).then((response) => response.json())
.then((responseJson) => {
console.log(JSON.stringify(responseJson)
return responseJson // <-- This part was missing
})
.catch((err) => console.log(err))
}
Second problem is that you're getting redirected when your form is submitted, am I right? Thus, you need prevent this default form behaviour by adding a event.preventDefault() in the beginning of your handleSubmit method:
handleSubmit(event) {
event.preventDefault()
// ... other code here
}

Related

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

Iterate Rails Array of Objects in React-Native

I'm trying to iterate an Array of Objects (retrieved from an ActiveRecord query) in a react-native app to render inside a table.
ActiveRecord query
def list
render json: Client.select('name, created_at, id').order('created_at DESC')
end
And this is how i am obtaining the data from the API (react):
getStatus() {
fetch(global.api_clients, {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Token token=' + global.token,
},
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({
clients: responseJson
});
})
.catch((error) => {
console.error(error);
});
}
Query output
Array [
Object {
"created_at": "2019-05-08T11:33:06.573Z",
"id": 1,
"name": "Francesco",
},
]
Rendering
render() {
const state = this.state;
const listItems = state.clients.map((link) =>
<Row data={link.name} textStyle={styles.text}/>
);
console.log(this.state.clients);
return (
<View style={styles.container}>
<Table borderStyle={{borderWidth: 2, borderColor: '#c8e1ff'}}>
<Row data={state.tableHead} style={styles.head} textStyle={styles.text}/>
{listItems}
</Table>
</View>
)
}
undefined is not a function (near '...data.map...')
Found it.
Error was in Row data, since it pretends an array.
Solved this way:
<Row data={[link.name, link.id, link.name]} textStyle={styles.text}/>

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

How to add a BearerToken to React API Requests?

newbie to React looking for some help... I'm using React to make API requests like so:
class CatsApi {
static createCat(cat) {
const request = new Request('http://localhost:4300/api/v1/cats', {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: JSON.stringify(cat)
});
return fetch(request).then(response => {
return response.json();
}).catch(error => {
return error;
});
}
Meanwhile, I have authentication to my API via react-devise:
https://github.com/timscott/react-devise
Which has a method getBearerToken like so: https://github.com/timscott/react-devise/blob/master/src/actions/authTokenStore.js
How do I use getBearerToken to pass the API the token so API requests are authenticated with the token?
Thank you!
You can use the Authorization header like:
{ 'Authorization': `Bearer ${authToken}` }
Using fetch you could try with something like:
fetch('http://localhost:4300/api/v1/cats', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`
'Accept' : 'application/json',
'Content-Type' : 'application/json',
},
body: JSON.stringify({
cat : cat_value,
})
})
.then((response) => response.json())
.then((responseData) => { console.log(responseData) })
.catch((error) => { console.log(error) })
.done()
Also, it'd be great to see what's the Rails output in the console when you make a request, or the browser console.

how to pass value entered in textinput to the url?

Hey guys i am trying to create search with back-end API in react native and i have to pass the word entered into the TextInput to the url. I am not sure whether i am doing it correctly or not can any body help me in rectifying
Here is the code.
this.state = {
search: "",
}
async onSearchPressed() {
try {
let response = await fetch("http://www.endpoints.com/search/{this.state.search}", {
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
});
render = () => {
let fields = [
{ref: 'search', placeholder: 'search', keyboardType:'default',secureTextEntry: false},];
return (
<TextInput
{...fields[0]}
onChangeText={(val) => this.setState({search: val})}
value={this.state.search}
/>
<TouchableOpacity onPress={this.onSearchPressed.bind(this)} />
It looks like, It taken the {this.state.search} as the string.
Change
let response = await fetch("http://www.endpoints.com/search/{this.state.search}", {
to
let response = await fetch("http://www.endpoints.com/search/"+this.state.search, {
What you are trying to use is https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals.
It should go like:
fetch(`http://www.endpoints.com/search/${this.state.search}`

Resources