I hava a problem (404 : Bad request ) when consuming token API in my react APP .
In Post man, it work very well
const requestOptions = {
method: 'POST',
mode: "no-cors", // no-cors, cors, *same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "include", // include, *same-origin, omit
redirect: "follow", // manual, *follow, error
referrer: "no-referrer", // no-referrer, *client
headers: {
},
body: JSON.stringify({
"client_id": "1_15dpzlnknhtwk8sgo4gwo800okogc4g00gk4k04g4g0cgc0ww0",
"client_secret": "dc86f30rr6okw8w84c8owkcko08s4k8k4c4c4k04osow8skko",
"grant_type": "password",
"username": "demoUsername",
"password": "demoPassword"
})
};
fetch('http://localhost:8000/oauth/v2/token', requestOptions)
.then(function(response) {
console.log('response');
console.log(response);
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});
the result is :
this is my security.yml
It's a problem of header.the header is empty
It's work now
Related
i am working on react axios, i run the axios call, you can see i setup the http api call, but when i run the code, it call https api, can anyone please help me why it is doing that ? any help will be really appreciated.
await axios({
method: 'Post',
//url: `${helper.ApiUrl}auth/signin`,
url : 'http://xx.xx.xx.xx/',
responseType: 'json',
// withCredentials: true,
// credentials: 'same-origin',
headers: {
"Access-Control-Allow-Origin": "*",
'Access-Control-Allow-Credentials': 'true',
"Access-Control-Allow-Headers": "Content-Type, Authorization",
mode: 'no-cors',
},
data: {
'email': email,
'password': password,
}
}).then((response) => {
res = response
});
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
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.
I am getting network error while doing axios.post request.
axios.post({
method:'POST',
url:'http://xxx.xxx.xxx.xxx:6310',
withCredentials: true,
auth: { username: 'username',
password: 'password'},
headers: {'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'},
data :{"jsonrpc":"1.0", "method":"liststreams","params":[]}
}).then(function(response) {
console.log('res ------- ',response)
}).catch(function(error) {
console.log('error =',error)
})
Thanks,
I am doing a POST request to auth api with a username and password and expecting a token in the response.
fetch('https://auth.entranceplus.in/auth', {
credentials: 'omit',
method: 'POST',
mode: 'cors',
body: JSON.stringify({
"username": this.userName.value,
"password": this.password.value
}),
headers: new Headers({
'Access-Control-Allow-Origin': '*',
'Accept': 'application/json',
'Content-Type': 'application/json',
'Data-Type': "json"
})
}).then(function (response) {
if (response.status === 200) {
return response.json();
} else if (response.status === 503) {
this.setErrorMessage('Failed to check-out license');
} else {
this.setErrorMessage('Incorrect Username or Password');
}
}.bind(this)).then(json => {
localStorage.setItem('username', this.userName.value);
localStorage.setItem('accesstoken', json.access_token);
});
As you can see in the image Request URL is http://localhost:3000/?username=dfbfdjhgfk&password=76895jfjg
My question is why the request not getting posted to https://auth.entranceplus.in/auth