I searched a lot on the Internet, but I didn't find anything helpful for my problem.
I have a java server and a react client. My server is using jwt for authentication and returns a token to my client.
When I try to send data with a post method, my client does not send the headers, so my server returns an "Unauthorized" message. I tried to send the same request from Postman and ARC(Advanced Rest Client) and it works.
Here is my client code:
fetch(url, {
method: 'POST',
crossDomain: true,
mode: 'no-cors',
body: JSON.stringify(data),
headers: {
'Authorization': 'Bearer ' + 'token generated from fiddler after running auth',
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(responseJson => {
console.log(responseJson);
});
I tried using axios too and I have the same problem.
Also my server has #CrossOrigin(origins = {"*"}) annotation in all controller classes.
I don't know if my problem is with the client or with the server and why is working using Postman and ARC.
You are using mode: no-cors which basically strips out all headers which are not simple headers: https://developer.mozilla.org/en-US/docs/Web/API/Request/mode
You should enable CORS and allow your domain on the server.
Related
Backend is Spring boots. I setup cookie there and it is working fine with postman.
#CrossOrigin(origins = "http://localhost:3000", allowCredentials = "true")
//Spring boots (http://localhost:8080)
Cookie cookie = new Cookie("access-token",token);
cookie.setPath("/");
cookie.setSecure(false);
response.addCookie(cookie);
response.addHeader("Access-Control-Allow-Credentials", "true");
Front End is ReactJS, I've used a POST method using Axios to get Login information.
I am getting response, but cookies are not set.
//React JS (http://localhost:3000)
axios({
url: common.url + '/login',
data: "userId=" + userid+ "&password=" + password,
method: 'post',
cache: false,
contentType: 'application/x-www-form-urlencoded',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8', 'Cache-Control': 'no-cache','withCredentials':'true'
}
}).then(function (result) {
;
//Success Login
})
Tried many things. No Luck
You need some more setup on the Cookie for it to work as what you expect
cookie.setPath("/") if you want it to be included in any requests.
If you are running your application in a non-https mode, you need to cookie.setSecure(false), otherwise, the browser will just ignore it.
If you want the cookie to be httpOnly, do cookie.setHttpOnly(true)
There're plenty more setups but those three should give you a decent result
Got a fix finally.
axios.post(url+'/login', { json }, { withCredentials: true }).then(function (result) {
}
WithCredentials should be passed like this from front-end.
in Backend code, along with the Crossorigin management, we need to add allowCredentials to true
I copied postman code and try to run it from the ReactJS app but it is giving error "Uncaught Error: Error: Invalid URI "/dologin"
I also used setupProxy.js file in the reactjs app but it is not working.
Here is my code from Postman.
var request = require("request");
var options = {
method: 'POST',
url: 'http://x.x.x.x:8080/dologin',
headers: {
'postman-token': 'b8754e2-974a-98fc-08e8-d40215dd226c',
'cache-control': 'no-cache',
'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YW21547gW'
},
formData: {
username: 'username',
password: 'password'
}
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
If I remove CORS from the server then I am able to get the response but token is not coming in the header, however it is coming if I use Postman.
Please help, thanks
The error message
error : use 'application/json' Content-Type and raw POST with json
data
is being appeared from cyclos application inside plivo console which a third API that need to be integrated in cyclos through
Gateway URL: https://api.plivo.com/v1/Account/auth-id/Message/
HTTP username:xxx
HTTP password: ****
HTTP headers
{
'content-type': 'application/json',
}
HTTP request type: POST
HTTP request POST body
{
"src":"+xxxx",
"dst":"+xxx",
"text":"some test"
}
Can you try sending header as 'Content-Type' instead of 'content-type'.
There are some implementations where field-names are case-sensitive (Like an age-old bug in PHP!).
I am building my application in Angular 2 and Laravel 5.4. Angular2 is for client side and laravel 5.4 is for server side. I created APIs in laravel and requesting those APIs from Angular2.
In Laravel, I configured Oauth 2 passport service which is authenticating all APIs. In each API call I am sending below headers.
'Content-Type', 'Authorization'
The way how I am calling APIs with headers.
private headers = new Headers({'Content-Type': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem('access_token') });
let body = JSON.stringify({ user_id, company_id });
console.log(this.headers);
this.http.post(this.BuyerCostSetting, body, {headers:this.headers} )
.subscribe(
response => {
console.log('here');
console.log(response);
},
error => {
console.log(error.text());
}
);
When I am hitting this API from Angular2, it is showing the below error:
Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response
The errormessage is clear, 'Authorization' header is not allowed by your backend.
In your backend Laravel application you have to set a response header containing:
Access-Control-Allow-Headers : 'Content-Type', 'Authorization'
see further documentation here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
I am getting this error
org.apache.coyote.http11.Http11Processor.service Error parsing HTTP request header
Note: further occurrences of HTTP header parsing errors will be logged at DEBUG level.
java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens
I have an app https://test.com where I make a call to backend server to retrieve files from cloud storage like amazon s3. The backend call is https://backend.com/api/getFile
example of spring boot controller
#RequestMapping(value = "/api/getFiles", method = RequestMethod.POST)
public ResponseEntity<?> getAllFules(#RequestBody String test){
try{
//some code
return new ResponseEntity<Object>("ok", HttpStatus.OK);
}catch(Exception e){
return new ResponseEntity<Object>("not ok", HttpStatus.BAD_REQUEST);
}
}
The backend server has a nginx running which routes to proxy_pass http://127.0.0.1:8080/
The client http code is like this in angular
$http({
url: 'https://www.backend.com/api/getFiles',
method: "POST",
data: auth.profile['email']
})
.then(function(response) {
console.log(" post success get files");
},
function(response) { // optional
// failed
console.log("post failed get files");
})
I also got the same error when i was trying to call https://localhost:7002 (weblogic) to http://localhost:8080 (tomcat).
You need to enable SSL in both servers.if you are using two servers. because as i see, your http://127.0.0.1:8080/ is not ssl enabled server.