Error is coming while hitting api
createUserProfile=async()=>{
try {
let response = await fetch(baseUrl + 'edituserprofilesave', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
hash: this.state.hash,
timestamp:this.state.timestamp,
id:this.state.id,
firstName:this.state.textFirstName,
lastName:this.state.textLastName,
picture: this.state.avatarSource.uri
}),
});
let responseJson = await response.json();
// alert("my response" + JSON.stringify(responseJson))
alert("success")
} catch (error) {
alert(error);
}
}
I know where error is coming..It is not taking textFirstName and textLastName which i am getting from here..
<FloatingLabelInput
label="First Name*"
onChange={value => {
this.setState({ textFirstName: value });
}}
style={[
styles.FloatingLabelInputStyle,
{ borderBottomColor: this.state.firstNameBorder }
]}
/>
and similarly textLast name ..I am updating state value but i don't know why it is throwing this error ..
Than you in advance
Related
I'm currently working on building out a Hubspot email submission form through nextjs and typescript but keep getting a few error and not sure how to solve. The first one is an error with my 'response' constant saying it's declared but not used and not sure how to solve and the second error is a 404 axios error. Not sure what I'm doing wrong.
Here's the api:
import axios from 'axios'
import type { NextApiRequest, NextApiResponse } from 'next'
const HUBSPOT_API_KEY = process.env.HUBSPOT_API_KEY
const HUBSPOT_PORTAL_ID = '22316985' // Replace this
const HUBSPOT_FORM_GUID = '5d0cab17-2376-44bc-bbe9-cb477bff0360' // Replace this
type Response = {
success: boolean
email?: string
}
export default async (req: NextApiRequest, res: NextApiResponse<Response>) => {
const { email, pageUri } = req.body
if (typeof email !== 'string') {
return res.status(400).json({ success: false })
}
try {
// eslint-disable-next-line #typescript-eslint/no-unused-vars
const response = await axios({
method: 'POST',
// eslint-disable-next-line no-useless-escape
url: `https://api.hsforms.com/submissions/v3/integration/secure/submit/${HUBSPOT_PORTAL_ID}/${HUBSPOT_FORM_GUID}/?hapikey/=${HUBSPOT_API_KEY}`,
data: {
fields: [{ name: 'email', value: email }],
context: { pageUri }
},
headers: { 'Content-Type': 'application/json' }
})
} catch (error) {
return res.status(500).json({ success: false })
}
res.status(200).json({ success: true, email })
}
Here's the index.tsx file:
const [email, setEmail] = useState('')
const [pageUri, setPageUri] = useState<string>()
const [{ loading }, refetch] = useAxios(
{
url: '/pages/api/emailSignup',
method: 'POST',
data: { email, pageUri }
},
{
manual: true
}
)
useEffect(() => {
if (data?.success === true && !loading) {
setEmail('')
}
}, [data?.success, loading])
useEffect(() => {
setPageUri(window.location.href)
}, [])
<Container className={s['pre__footer']}>
<Isotype className={s['isotype']} />
<Heading
as="h2"
variant="md"
centered
style={{ textTransform: 'capitalize' }}
>
Sign-up for our <br /> Newsletter
</Heading>
<input
type={'email'}
placeholder={'Enter your email to stay updated'}
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<button
type={'submit'}
onClick={() => refetch()}
disabled={loading}
>
<ArrowLink />
<span className="sr-only">Send</span>
</button>
</Container>
Regarding the first error, if you're not using response then don't include it, it's as simple as that. You'd only need it if you want to use whatever is being returned from the POST request to the API, and it seems that's not the case.
The second error: You're getting a 404 error because you're calling your endpoint incorrectly. It should be:
const [{ loading }, refetch] = useAxios(
{
url: '/api/emailSignup', // removed "/pages" from this line
method: 'POST',
data: { email, pageUri }
},
{
manual: true
}
)
This is because any file inside the folder pages/api is mapped to /api/* and will be recognized as an API endpoint instead of a page. This means that if your page is https://example.com you can access your emailSignup API endpoint on https://example.com/api/emailSignup.
EDIT: While reading Hubspot's docs, I noticed what could be a slight mistake in the url you're making a request to, please try this modification on your API endpoint and let me know if it works:
export default async (req: NextApiRequest, res: NextApiResponse<Response>) => {
const { email, pageUri } = req.body
const { method } = req
if (method !== 'POST') {
return res.status(405).end()
}
if (typeof email !== 'string') {
return res.status(400).json({ success: false })
}
try {
await axios({
method: 'POST',
// eslint-disable-next-line no-useless-escape
url: `https://api.hsforms.com/submissions/v3/integration/secure/submit/${HUBSPOT_PORTAL_ID}/${HUBSPOT_FORM_GUID}?hapikey=${HUBSPOT_API_KEY}`,
data: {
fields: [{ name: 'email', value: email }],
context: { pageUri },
},
headers: { 'Content-Type': 'application/json' },
});
res.status(200).json({ success: true, email })
} catch (error) {
return res.status(500).json({ success: false })
}
}
On a vue application, on a component, calling API to get some data... the problem is that getting undefined, before the call ends... Possible needed aync/await but getting error when adding
//component code (login.vue)
import store from "#/store";
const { response, error } = store.postTO(url, [{id: "button1"}, {id: "button2"}, {id: "button3"}]);
if (response) {
console.log(response);
} else {
console.warn(error);
}
//store.js
export default {
user : null,
postTO
}
function postTO(url, postData) {
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: JSON.stringify(postData)
};
return fetch(url, requestOptions).then(response =>
response.json().then(data => ({
data: data,
status: response.status
})
).then(res => {
console.log(res.data);
return {response : res.data, error : "test"};
}))
.catch(error => {
return {response : "test", error : error};
});
}
illustrated
In the component you have to wait for the fetch by putting an await before the store.posTo
I am having problems using 'nested' Fetch calls within a React Native function. It seems the first Fetch works correctly, however an error is thrown on the second. Here is the code:
//****CALL TWO FETCH REQUESTS...
const data = { passkey: '12345', callup: 'name' };
const secondary = { passkey: '12345', callup: 'name' };
fetch('https://myremoteserveraddress', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(function(response) {
if (response.ok) {
return response.json();
} else {
return Promise.reject(response);
}
})
.then(data => {
// Store the post data to a variable
_post = data;
console.log('Success on FIRST FETCH:', data);
console.log('answer is:', data.answer);
console.log('answer is:', _post.answer);
// Fetch another API
fetch('https://myremoteserveraddress', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(secondary),
})
})
.then(function (response) {
if (response.ok) {
return response.json();
} else {
return Promise.reject(response);
}
})
.then(function (userData) {
console.log('Returned from BOTH fetch calls'); //does not write to console
console.log(_post, userData); //does not write to console
this.vb.start();
})
.catch((error) => {
console.error('Error in onPressPublishBtn:', error);
});
//****
It seems the second Fetch call returns 'undefined', despite being identical to the first Fetch call which seems to work successfully. The error returned is "TypeError: undefined is not an object (evaluating 'response.ok')". If anybody can advise on what the problem may be I would be greatly appreciative. Thank you in advance.
You should return a Promise from the second then(...) block so that the response is passed to the third then(...) block. You might want to try something like this:
// Fetch another API
return fetch('https://myremoteserveraddress', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(secondary),
})
I had a problem sending data to the server.
when I try to submit data via postman successfully with the response below
and if I activate
'Content-Type': 'application / json'
i have a problem that is
JSON Parse error: Unrecognized token '<'
{
"status": 200,
"message": "success login",
"id_kurir": "3",
"username": "tester",
}
When I try with code, I get an error that is [object object]
this my code :
constructor(props) {
super(props);
this.state = {
Uname : '',
Upass : ''
}
}
login= ()=>{
const {Uname,Upass} = this.state;
fetch('https://example.com/login', {
method: 'POST',
// headers: {
// 'Accept' : 'application/json',
// 'Content-Type': 'application/json'
//},
body: JSON.stringify({
username: Uname,
password: Upass
})
})
.then((response) => response.json())
.then((responseJson) => {
alert(responseJson);
console.log(JSON.stringify(responseJson));
}).catch((error)=>{
console.log(error);
})
Keyboard.dismiss();
}
<Form style={styles.mainForm}>
<Item style={styles.formItems}>
<Input placeholder="Username" style={styles.Input} onChangeText={Uname => this.setState({Uname})}/>
</Item>
<Item style={styles.formItems}>
<Input style={styles.Input} secureTextEntry={true} onChangeText={(Upass) => this.setState({Upass})}/>
</Item>
<View style={styles.Button}>
{/* <Button block style={styles.mainBtn} onPress={() => this.props.navigation.navigate('home')}> */}
<Button block info style={styles.mainBtn} onPress={this.login}>
<Text style={styles.btnText}>Submit</Text>
</Button>
</View>
</Form>
where is the fault?
The server probably a 404 or 500 error. Instead of response.json() use response.text() you will get the html in text.
I assume Your server is not taking JSON formatted body
Try using below code.
Option 1:
fetch('https://example.com/login', {
method: 'POST',
body: JSON.stringify({
username: Uname,
password: Upass
})
}).then(response => response.text()).then((text) => {
if (Platform.OS === 'android') {
text = text.replace(/\r?\n/g, '').replace(/[\u0080-\uFFFF]/g, '');
// If android, remove unwanted chars.
}
return text;
}).then(response => JSON.parse(response));
Option 2:
fetch('https://example.com/login', {
method: 'POST',
body: JSON.stringify({
username: Uname,
password: Upass
})
}).then((response) => response.text()).then((responseJson) => {
alert(JSON.stringify(responseJson));
console.log(JSON.stringify(responseJson));
}).catch((error) => {
alert(JSON.stringify(error));
console.log(error);
})
I am writing a mobile application with using React Native. At some part, I need to send a post request and get response including the error part. So, for some certain input, API(my own) returns 409 with a message. Example return:
{
"status": 409,
"message": "E-mail is already exists!"
}
Here, I want to take that message and show to the user. This is what I tried:
UserService.signup({ fullName, email, username, password })
.then(response => {
this.setState({ signUp: true });
if (response.result) {
Toast.show(messages.successfulSignUp, {
backgroundColor: "green",
duration: Toast.durations.LONG,
position: Toast.positions.TOP
});
this.props.navigation.navigate("SignIn");
} else {
}
})
.catch(error => {
Toast.show(error.message, {
backgroundColor: "red",
duration: Toast.durations.LONG,
position: Toast.positions.TOP
});
this.setState({ signUp: false });
});
I tried error.message, error.response, error, error.data keys, but it always says TypeError: undefined is not an object (evaluating 'error.message'). So, how can I get the message from error object?
Edit: This is how I send the request:
import { post } from "./api";
export default {
signup: ({ fullName, email, username, password }) => {
return post("/user/register", { fullName, email, username, password });
}
};
export const request = config => {
return new Promise((resolve, reject) => {
axiosInstance
.request({
url: config.url,
method: config.method || "get",
data: config.body,
headers: {
"Content-Type": "application/json",
"X-Auth-Token": store.getState().auth.token
}
})
.then(response => {
resolve(response.data);
})
.catch(error => {
reject(error.data);
});
});
};
export const post = (url, body = {}) => {
return request({
url,
body,
method: "post"
});
};
Finally I solved this issue. I had to change my request method and the way I reach out to the error:
export const request = (config) => {
return new Promise((resolve, reject) => {
axiosInstance.request({
url: config.url,
method: config.method || 'get',
data: config.body,
headers: {
'Content-Type': 'application/json',
'X-Auth-Token': store.getState().auth.token,
}
}).then(response => {
resolve(response.data)
}).catch(error => {
reject(error.response)
})
})
}
// This is how reach out to the error message:
console.log(error.data.message);
Depending on what the backend returns, the error message in axios is in response.data of the error object.
.catch(error => {
const errResponse = (error && error.response && error.response.data)
|| (error && error.message);
reject(errResponse);
});