React axios ReactJS AXIOS post doesn't work - javascript

console error ->
[1]: https://i.stack.imgur.com/xOfUV.png
axios
.post("https://bootcamp-2022.devtest.ge/api/application", {
token: "7e475dfc-0daa-4108-81c8-d6c62a3df4ca",
first_name: JSON.parse(localStorage.getItem("PersonalInfo").first_name),
last_name: JSON.parse(localStorage.getItem("PersonalInfo").last_name),
email: JSON.parse(localStorage.getItem("PersonalInfo").email),
skills: JSON.parse(localStorage.getItem("techskill").skills),
work_preference: JSON.parse(
localStorage.getItem("covid").work_preference),
.then((res) => console.log(res))
.catch((err) => {
console.log(err);

As the error metioned you have an error on your json
This is your current code
first_name: JSON.parse(localStorage.getItem("PersonalInfo").first_name)
This is how it should be
first_name: JSON.parse(localStorage.getItem("PersonalInfo")).first_name
And you might want to hide the api and the token .

Related

Mailchimp post request in react giving error

I am making my web using React no backend. I want to integrate MailChimp to my app but it's giving me the following error:
ContactUs.jsx:40 POST http://localhost:3000/3.0/lists/{api-key} 404 (Not Found)
function sendData(event) {
const { name, email, subject } = state;
const userData = {
members: [
{
"email_address": email,
status: "subscribed",
merge_fields: {
"FNAME": name,
"MESSAGE": subject,
}
}
]
}
console.log(userData)
fetch('/3.0/lists/{api-key}', {
method: 'POST',
headers: {
'auth': "saad:153b-us12",
'Content-Type': 'application/json',
},
body: JSON.stringify(
userData
)
}).then(response => console.log(response))
.catch(error => console.error(error))
event.preventDefault();
}
You are sending the request to the localhost, which is your app url on your machine. According to the Mailchnimp docs you should send the request to https://<dc>.api.mailchimp.com url. Just set the correct url in the fetch function.

React Router Adds URL Query Params on POST Request

Hello my fellow nerds,
I am running into an issue where when I make a POST request (using Axios library inside of React function), it automatically appends all of the data from the "Create a User" form into search parameters in the URL of the page upon submission. I don't like this because I'd rather this stay hidden within the POST request, not flung out onto the page URL.
Image: URL after user was created
This is a direct result of React Router adding the data sent in the request of the body being appended to the location.search of react router's history object. So, naturally, since the react router history object is mutable, I tried adding this to the response of the submission:
this.props.location.search.replace({*some random parameter stuff here*});
This was in hopes it would remove all of that stuff from the URL and redirect to the page without search parameters. Anyways, I have seen a few other posts similar in nature but they don't seem to answer this exact question.
TL;DR: I am trying to send a POST request without React Router adding my req.body data to the params in my URL and the location.search object.
MY CODE:
Users.js: (front end)
handleSubmit (e) {
Axios.post(`${server}/s/admin/users/create`, {
headers: {
'Content-Type': 'application/json'
},
data: {
firstName: this.state.firstName,
lastName: this.state.lastName,
username: this.state.username,
password: this.state.password,
email: this.state.email
}
}).then((res) => {
console.log(res);
}).catch(err => console.log(err));
}
users.js: (back end)
app.post("/s/admin/users/create", (req, res) => {
let rb = req.body.data;
let newUser = new User({
_id: uid.time(),
orgID: req.session.orgID,
email: rb.email,
username: rb.username,
password: bcrypt.hashSync(rb.password, hashRate),
firstName: rb.firstName,
lastName: rb.lastName,
data: { exist: "true" },
settings: { exist: "true" }
});
// Save new owner to db
newUser.save((err, data) => {
if (err) return console.error(err);
res.json({info: `A new user, ${newUser.firstName} ${newUser.lastName}, has been created successfully.`});
});
});
Thank you!
P.S. This is my first post, thank you for your patience. I've tried searching and solving this issue for about a day now.
Can you try rewriting it this way? cause axios.post expect
axios({
method: 'post',
url: `${server}/s/admin/users/create`,
headers: {
'Content-Type': 'application/json'
},
data: {
firstName: this.state.firstName,
lastName: this.state.lastName,
username: this.state.username,
password: this.state.password,
email: this.state.email
}
}).then((res) => {
console.log(res);
}).catch(err => console.log(err));
Axios.post method expect the second argument as data but you have passed config, another way is to pass data and config in the third argument.
handleSubmit(e) {
Axios.post(`${server}/s/admin/users/create`, {
firstName: this.state.firstName,
lastName: this.state.lastName,
username: this.state.username,
password: this.state.password,
email: this.state.email
}, {
headers: {
'Content-Type': 'application/json'
}
}
}).then((res) => {
console.log(res);
}).catch(err => console.log(err));
}

Axios post request not working with Django Rest Framework

I am trying to use Axios post to create a user in my Django Rest Framework api.
Currently getting "Request failed with status code 400" when trying to post.
It works perfectly fine in postman.
drfServer.js
import axios from 'axios';
export default axios.create({
baseURL: 'https://example.com'
});
AuthContext.js
const signup = (dispatch) => async ({ email, password }) => {
try {
const response = await drfApi.post('/user/',
{
data: {
username: email,
password: password
}
}
);
// await AsyncStorage.setItem('token', response.data.token);
// dispatch({ type: 'signin', payload: response.data.token });
// navigate('Task')
} catch (err) {
console.log(err.message)
dispatch({ type: 'add_error', payload: 'Something went wrong with sign up' })
}
};
I tried using fetch and it works. But with Axios I am not getting it right.
Any ideas how to make it work?
Can you try this code.
const signup = ({email,password}) => dispatch => {
return axios({
method: "post",
url: "your api url",
data: {
username: email,
password
})
.then(result => {
console.log(result.data);
})
.catch(error => {
console.log(error);
})
};
You can find the axios example code here https://github.com/axios/axios
Maybe you can try this :
const response = await drfApi.post('/user/', {
username: email,
password: password
}
);
As using axios.post will automatically take the 2nd param and make it an object with data key

React / Javascript Variables

I'm attempting to pass an Object from one Class to another which are in separate files. The overall goal is to consolidate my API calls into a single .js file for reference throughout the app.
The issue I'm having here is I'm unable to access the variables within the object within the .js file that calls the class.
Scenario:
I make my API calls in APICall.js and then attempt to pass the response data back to Page.js. I'm able to see my object in Page.js; however, I can't seem to access any of the variables to update my state.
Note: I'm new to ReactJS (and Javascript) with a solid Python background. Obviously these are two completely different beasts here.
Appreciate any assistance anyone can provide!
Console Logs Issues
:20 Object appears empty but shows values when extending.
:21 is a blank line but should be logging the first_name
:30 is a blank Object all together
--
TESTING !##
UpperNavigation.js:20 {first_name: "", last_name: "", email: "", company: ""}
company: "Testing 123"
email: "john#somewebsite.com"
first_name: "John"
last_name: "Doe"
__proto__: Object
UpperNavigation.js:21
UpperNavigation.js:30 {first_name: "", last_name: "", email: "", company: ""}
company: ""
email: ""
first_name: ""
last_name: ""
__proto__: Object
Page.js
state = {
first_name: '',
last_name: '',
email: '',
company: ''
}
componentWillMount() {
// this.getUserProfile.bind(this)
var userData = new vAPI().getUserProfile()
console.log("TESTING !##");
console.log(userData)
console.log(userData.first_name);
this.setState({
first_name: userData.first_name,
last_name: userData.last_name,
email: userData.email,
company: userData.company
});
console.log(this.state);
}
APICall.js
import axios from 'axios';
export default class vAPI {
constructor() {
this.state = {
first_name: "",
last_name: "",
email: "",
company: ""
}
}
getUserProfile(){
const URL = "https://somewebsite.com/api/user_profile/"
const USER_TOKEN = localStorage.getItem('access_token')
const AuthStr = 'JWT '.concat(USER_TOKEN);
axios.get(URL, { headers: { Authorization: AuthStr } }).then(response => {
this.state.first_name = response.data.first_name
this.state.last_name = response.data.last_name
this.state.email = response.data.email
this.state.company = response.data.company
}).catch((error) => {
console.log('error 3 ' + error);
});
return (this.state);
};
}
In getUserProfile() you are returning this.state before your axios get request is complete. When you call getUserProfile() from Page.js you are trying to access the data before it is set from your get request.
You should be returning the promise in getUserProfile() then using async/await or .then() when you call it in componentWillMount() before setting the data
getUserProfile(){
const URL = "https://somewebsite.com/api/user_profile/"
const USER_TOKEN = localStorage.getItem('access_token')
const AuthStr = 'JWT '.concat(USER_TOKEN);
return axios.get(URL, { headers: { Authorization: AuthStr } })
};
async/await
async componentWillMount() {
const userDataRes = await (new vAPI().getUserProfile());
const userData = userDataRes.data;
this.setState({
first_name: userData.first_name,
last_name: userData.last_name,
email: userData.email,
company: userData.company,
});
console.log('state', this.state);
}
promise
componentWillMount() {
new vAPI().getUserProfile().then((userDataRes) => {
const userData = userDataRes.data;
this.setState({
first_name: userData.first_name,
last_name: userData.last_name,
email: userData.email,
company: userData.company,
});
console.log('state', this.state);
});
}

http-client call a function on response arrival

let's say I have a service that is sending a post request to my API, and as soon as the response has arrived, I'd like a custom function to be executed as part of the process.
public signin(){
return this.http.post<any>(`${env.API_URL}/user/signin`, { username: user.username, password: user.password }).toPromise();
}
I have tried using the pipe operator, but for some reason it wasn't sending errors to the returned promise.
public signin(){
return this.http.post<any>(`${env.API_URL}/user/signin`, { username: user.username, password: user.password }).pipe(
tap(
data => this.customFunction(data),
error => error
)
).toPromise();
}
One option is to use code like this:
getMovies(): Observable<IMovie[]> {
return this.http.get<IMovie[]>(this.moviesUrl).pipe(
tap(data => console.log(JSON.stringify(data))),
catchError(this.handleError)
);
}
You could then add your custom function in the tap.
So your code would look more like this:
public signin() {
return this.http.post<any>(`${env.API_URL}/user/signin`, { username: user.username, password: user.password }).pipe(
tap(data => this.customFunction(data)),
catchError(error => console.log(error))
);
}
You can do this using the following code:
public signin() {
return this.http.post<any>(`${env.API_URL}/user/signin`, { username: user.username, password: user.password })
.toPromise()
.then((data) => {
this.customFunction(data)
})
.catch(this.handleError);
}
Then just define a handle error function, or use a lambda function just like with data if you prefer

Categories