headers are not being set into AXIOS post request - reactjs

I am working on react-redux App. When i am making Api Post request to Rest Api(on CORS). Headers are not being set. But when i try this in postman it work perfectly.
this is the code:
I want to send TOKEN(for testing).
post: (endPoint, data) => {
return axios({
method: 'post',
url: `${apiPath}/${endPoint}`,
data: data,
headers: { "Content-Type": "application/json", 'TOKEN': 1111}
}).then((res) =>{
return res;
})
}

Related

Getting 400 Error while Authenticating user credentials using fetch API

I am using asp.net core as backend and react as a front-end. I am using fetch API to authenticate user credentials.
But when I am trying to log in I am getting a 400 error. Everything is working fine on the postman.
Here is my react code:
const submitLoginForm = async (e) => {
e.preventDefault();
await fetch("https://localhost:44316/api/auth/login", {
method: 'POST',
headers: {"Content-Type": "application/json"},
credentials: 'include',
body: JSON.stringify({
email,
password,
})
});
setRedirectTo(true);
};
I am calling the above function on form submit.
Just add the => Accept: "application/json" in headers section
const submitLoginForm = async (e) => {
e.preventDefault();
await fetch("https://localhost:44316/api/auth/login", {
method: 'POST',
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
email,
password,
})
});
setRedirectTo(true);
};

How to pass Cache-Control in axios headers?

I have tested on postman and when I pass 'Cache-Control' : 'max-age=0' ,the API gives the correct response.
But When I try to pass it from the Front end side, I am getting CORS error.
Here is how I am passing -
export function getDuplicateDataFromCache(url) {
return (dispatch) =>
axios({
method: 'get',
url: `${API}cache/test/${url}`,
data: {},
headers: {
'Cache-Control': 'max-age=0',
},
})
.then((response) => {}

Fetching an API in react

I am new to React, And I am Stuck. I am trying to make a signup page, having textboxes: name,phonumber,email,password.
What I want is, When I click on login button, all these details should be sent over POST to my API, and response is fetched and stored.
API:
http://localhost:5000/api/users/signup
Method:
POST
Request to my api is send in this way:
content-type: application/json
{
"name": "Devanshh Shrivastvaaaa",
"phoneNumber":"982964XXX8",
"email": "devannnnnshh;#ccc.in",
"password": "1234566788"
}
Can anyone please explain me using code how to send this data to my api on clicking signup, and fetching response
Don't need to use any third party libraries, just use the Javascript fetch API
// Example POST method implementation:
async function postData(url = '', data = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}
postData('https://example.com/answer', { answer: 42 })
.then(data => {
console.log(data); // JSON data parsed by `data.json()` call
});
Source: Mozilla MDN
you need to install axios or fetch axios is good axios
axios.post('http://localhost:5000/api/users/signup', {
name: "Devanshh Shrivastvaaaa",
phoneNumber":"982964XXX8",
email: "devannnnnshh;#ccc.in",
password: "1234566788"
})
.then((response) => {
console.log(response);
}, (error) => {
console.log(error);
});
also check for further

Set cookie from API response in React

I have a React app, and an API. When i POST data to APIs login url API responses me back with cookie on successful login, which I have to set, so in each next request user will send this cookie. But I can't find a method to get it from response.
I want to set sessionid, but I can't reach it within code. I tried to do
Cookies.set('sessionid', response.headers['sessionid']);
But it sets undefined. console.log(response.headers) also gives me {content-length: "31", content-type: "application/json"}. Do I do something wrong?
Sender function:
formSender() {
const url_to_send = `${this.state.api_base_url}:${this.state.api_base_port}${this.state.api_user_url}/login/`;
axios.post(url_to_send, `username=${this.state.username}&password=${this.state.password}`, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
.then((response) => {
// I need to set the cookie here
this.setState({
login_success: response.status === 200,
request_sent: false
});
})
};
Try to set Access-Control-Expose-Headers in the back end or
await axios({
method: 'post',
url: YOUR_URL,
data: Data,
headers: { 'Authorization': 'TOKEN' }
});
I have the same problems and i do that for resolve in backend:
app.use(cors({
origin: true,
credentials: true
}));
and the axios request :
axios({
method: "post",
url: `http://localhost:5500/api/user/login`,
withCredentials: true,
data: {
email,
password,
},
headers: {
"Content-Type": "application/json",
}
})
.then((res) => {
console.log(res);
})
I was initially looking for a solution to setting a cookie from a response, but I realized if it's passed as a Set-Cookie header then it is set by the browser. No need to set it manually. Here is the console view
My app looks something like this:
const app = express();
app.use(cors({
origin: ['http://localhost:3000'],
methods: ['POST', 'PUT', 'GET', 'OPTIONS', 'HEAD'],
credentials: true,
}))
app.use(cookieParser())
app.get('/foo', verifyToken, (req, res) => {
// you can omit verifyToken if you want, it's for bearer auth.
if (true) {
res.cookie('XSRF-TOKEN', 'example')
res.send('Welcome')
} else {
res.sendStatus(403);
}
});
The React side:
<Button onClick={() => {
axios.get('http://localhost:8081/foo', {
params: {},
headers: {
Authorization: `Bearer 123`,
// again, omit ^ if you're not doing bearer auth
},
withCredentials: true,
}
).then((response) => {
console.log('cookie should be set')
})
}}>Express cookie</Button>
Bear in mind if you're deploying to a server both react and express should be on an https connection. Connecting http <-> https causes other issues with cookies.

API request working in Postman but not in fetch() method of React Native app

I am trying to do a fetch() method in my React Native app:
return fetch(url, {
method: method,
headers: {
'Accept': 'application/json',
...headers
},
body: body
})
Here url is <IP address>:<port>/api/token
method is 'POST'
headers is {Content-Type: "application/x-www-form-urlencoded"}
and body is
grant_type=password&username=<username>&password=<password>&pushtoken=&primaryhost=<primary host IP>&primaryport=<primary host port>&secondaryhost=<secondary host IP>&secondaryport=<secondary host port>&osscustomer=103&deviceid=<device ID>&version=1.0&osversion=9&deviceversion=1.0
When I use these values in a Postman request, it works fine, but when I run the fetch() method in my React Native app, it gives the error e = TypeError: Network request failed at XMLHttpRequest.xhr.onerror.
Does anyone know why this might be?
change 'Accept' to Accept without single quites.
In the latest android versions http requests are not allowed by default. Take a look at this post for further information about allowing http request:How to allow all Network connection types HTTP and HTTPS in Android (9) Pie?
Use the following format:
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
}),
});
Better to use axios for http/https requests:axios package
It's working fine for me. Try this it may help
const formData = new FormData();
formData.append('email', 'test#gmail.com');
formData.append('password', '123456');
fetch("https://test.com/api/login", {
method: 'post',
body: formData
})
.then(res => res.json())
.then(
(result) => {
console.log(result);
}).catch(err => {
console.log(err);
})

Resources