401 Unauthorized REST API in lightning web component salesforce - javascript

I'm trying to execute query using REST API, in a lightning web component.
the request in Postman returning result with success (enabling Follow Authorization header)
but in the JavaScript in lightning web component it returns 401 Unauthorized
the code in the java script is a follow :
let sessionId = 'tokken';
let baseUrl = window.location.origin;
let header = {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": "Bearer " + sessionId,
};
if (sessionId) {
let options = {
method: "GET",
mode: 'no-cors',
redirect: 'follow',
headers: header,
};
fetch(baseUrl + '/services/data/v50.0/query/?q=SELECT+name+from+Account', options).then((response) => {
console.log(JSON.stringify(response));
if (!response.ok) {
// throw Error(JSON.stringify(response));
} else {
return response.json();
}
}).then((repos) => {
console.log(repos, repos);
});
}
am I missing something ?

Since you can not pass the value Authorization to no-cors mode, you will need to add CORS configuration in your SalesForce as safe endpoint where they let you make a call.

You can not send Authorization header with "no-cors" mode.
mode: "no-cors"only allows a limited set of headers in the request:
Accept
Accept-Language
Content-Language
Content-Type with a value of application/x-www-form-urlencoded, multipart/form-data, or text/plain

Related

Content type 'text/plain;charset=UTF-8' not supported in fetch js ti api spring boot

I'm trying to send an http request using fetch to my backend but it's returning this error even though I'm sending an application/json header,
the content that needs to reach the api is a json
front-end code
let user_ = 'teste';
let email_ = 'teste#email.com';
let pass_ = 'teste';
let button_submit = document.getElementById('mySubmit_signup');
let headers = new Headers();
headers.append('Accept', 'application/json');
headers.append('Content-Type', 'application/json');
headers.append('Access-Control-Allow-Origin', '*');
headers.append('Access-Control-Allow-Credentials', 'true');
button_submit.addEventListener('click', async function(){
try {
await fetch('http://localhost:8080/users', {
mode: 'cors',
method: 'POST',
body: JSON.stringify({
name: user_,
email: email_,
password: pass_
}),
})
.then(
response => response.json()
)
.then(
data => console.log(data)
)
} catch (error) {
console.log(error);
}
});
ATT:
i add header but i receive "Access to fetch at 'http://localhost:8080/users' from origin 'http://localhost:7777' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."
try {
await fetch('http://localhost:8080/users', {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
},
body: JSON.stringify({
name: "user_",
email: "mail_#email.com",
password: "pass_"
}),
})
.then(
response => response.json()
)
.then(
data => console.log(data)
)
} catch (error) {
console.log(error);
}
};
req();
You are passing a string to body. This means fetch will automatically add a Content-Type request header saying that you are sending plain text.
Your server side code is expecting JSON and is rejecting your so-called plain text with an error.
You need to explicitly add the correct header to say that you are sending JSON.
headers: {
'Content-Type': 'application/json',
},
Aside Do not add 'Access-Control-Allow-Origin': '*', to your request headers. This is a response header and has no business being on the request. Adding it will create additional problems.
Adding an application/json content type to the request will make it preflighted.
You quoted an error mentioning a preflight request. The error state may have been caused by your incorrect extra header (see the aside above) or it might be that your server isn’t set up to support any preflight request.
If the latter then you need to adjust the server-side code to response to the preflight request (which is OPTIONS rather than POST) to give permission to the browser to make the POST request you want to make.

return error in front when permissions enable django rest

I have a view with permission_classes enabled
class ProjectCopyView(APIView):
permission_classes = [IsAuthor]
class IsAuthor(BasePermission):
'''Проверка права на авторство проекта'''
message = "Only the author of the project can share it"
def has_permission(self, request, view):
try:
if Project.objects.get(id=view.kwargs['project_id'], user=request.user):
return True
except:
return False
This works in postman, but when I try to repeat this request for js the error
Access to fetch at 'http://127.0.0.1:8080/api/editor/project/1/copy/' from origin 'null' has been thrown blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Django console gives 401 unautorized
async function testSizze(){
const res = await fetch("http://127.0.0.1:8080/api/editor/project/1/copy/", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Token 8fdc5648e07851c9ebe3c05f56b4c2400f2d90b9"
},
body: JSON.stringify({
})
});
const json = await res.json();
console.log(json)
}
When i disable permission_classes js the request works
fetch won’t send cookies, unless you set credentials: 'same-origin'.
const res = await fetch("http://127.0.0.1:8080/api/editor/project/1/copy/", {
method: "POST",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
"Authorization": "Token 8fdc5648e07851c9ebe3c05f56b4c2400f2d90b9"
},
body: JSON.stringify({
"to_user": "admin#mail.ru",
"permission": ["read"],
"all_users": "False"
})
});
So maybe you are using the wrong authentication setting for django-rest-framework?
I managed to solve the problem. This project was not developed by me, and I do not quite understand why this is. I added to my permission
if request.method == 'OPTIONS':
return True

"No Access control header is present" - while calling AWS lambda function through API

I have created a Lambda function in python, inside this function I have put header with cross origin details. Here is the code of my Lambda function:
def lambda_handler(event, context):
data=''
s3_boto = boto3.client('s3')
s3 = boto3.resource('s3')
reference_elements = event['data1']
test_elements = event['data2']
try:
#access first event object
imagePath = []
data= compute_data(reference_elements, test_elements)
return response({'message': data}, 200)
except Exception as e:
return e
return response({'message': data}, 200)
def response(message, status_code):
return {
'statusCode': str(status_code),
'body': json.dumps(message),
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
"Access-Control-Allow-Methods": "OPTIONS,POST,GET"
},
}
Now I have created a AWS API Gateway with POST method and enable CORS. Then I deployed this API.
While I am running this API from Postman it is working fine.
But once I try to fetch this API from my React JS code it is throwing the following error:
enter image description here
Here is my React Js code in button click:
let postData = {"key1":"value1","key2":"value2","key3":"value3"}
const requestOptions = {
method: "POST",
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Headers": "*"
},
body: JSON.stringify(postData)
}
const url =
"https://apiId.execute-api.us-east-1.amazonaws.com/apiFunctionName"
fetch(url, requestOptions)
.then(response => console.log(response))
.then(data => console.log(data))
Please correct me where I am going wrong, I have invested lots of time for trial and error but no luck.
Browsers before making a call to a cross origin, makes a preflight request using the OPTIONS method. In your network tab, you should be seeing an OPTIONS call, which in your case is not allowed on ApiGateway. Similar to the POST method you have allowed on gateway, allow OPTIONS call. Return the OPTIONS call with a 200 and the CORS headers, based on which domain you want to allow.

Setting Content-Type in fetch request not working

I am doing a remote fetch request to a server. The payload is in JSON format, so I want to change the Content-Type header to application/json. I have used the following code to do this:
let email = document.getElementById("email").value
let password = document.getElementById("password").value
const body = {"email":email, "password":password}
const headers = new Headers({
"Content-Type": "application/json",
"Content-Length": JSON.stringify(body).length
})
const options = {
method: "POST",
mode: "no-cors",
headers: headers,
body: JSON.stringify(body)
}
console.log(options)
const response = await fetch('http://xx.xx.xx.xxx/login', options)
const json = await response.json()
console.log(json)
However, in the Chrome developer tools console, the Content-Type header of the request is still text/plain;charset=UTF-8. What am I doing wrong?
Overriding the Content-Type request header is not allowed for no-cors requests.
Change the mode to cors.
(You won't be able to read the response without doing that either).

When using mode: no-cors for a request, browser isn’t adding request header I’ve set in my frontend code

in my React app, I have the following API POST to allow the user to edit their profile (name and image).
static updateProfile(formData, user_id) {
const request = new Request(`http://localhost:4300/api/v1/profiles/${user_id}`, {
headers: new Headers({
'Authorization': getBearerToken()
}),
mode: 'no-cors',
method: "POST",
body: formData
});
return fetch(request).then(response => {
return response.json();
}).catch(error => {
return error;
});
}
The problem with the above is the header with the Authorization token is not being sent in the POST...
How can I get the Authorization header to be send in the fetch request above?
FYI, for non-multipart forms, the authorization token is sent successfully like so:
static loadProfile(user_id) {
const request = new Request(`http://localhost:4300/api/v1/profiles/${user_id}`, {
headers: new Headers({
'Authorization': getBearerToken(),
'Accept' : 'application/json',
'Content-Type' : 'application/json',
})
});
return fetch(request).then(response => {
return response.json();
}).catch(error => {
return error;
});
}
You can’t use no-cors mode if you set any special request headers, because one of effect of using it for a request is that it tells browsers to not allow your frontend JavaScript code to set any request headers other than CORS-safelisted request-headers. See the spec requirements:
To append a name/value pair to a Headers object (headers), run these steps:
Otherwise, if guard is "request-no-cors" and name/value is not a CORS-safelisted request-header, return.
In that algorithm, return equates to “return without adding that header to the Headers object”.
Authorization isn’t a CORS-safelisted request-header, so your browser won’t allow you to set if you use no-cors mode for a request. Same for Content-Type: application/json.
If the reason you’re trying to use no-cors mode is to avoid some other problem that occurs if you don’t use, the solution is to fix the underlying cause of that other problem. Because no matter what problem you might be trying to solve, no-cors mode isn’t going to turn out to be a solution in the end. It’s just going to create different problems like what you’re hitting now.
By using below code you can make a fetch request with Authorization or bearer
var url = "https://yourUrl";
var bearer = 'Bearer '+ bearer_token;
fetch(url, {
method: 'GET',
withCredentials: true,
credentials: 'include',
headers: {
'Authorization': bearer,
'X-FP-API-KEY': 'iphone',
'Content-Type': 'application/json'}
}).then((responseJson) => {
var items = JSON.parse(responseJson._bodyInit);
})
.catch(error => this.setState({
isLoading: false,
message: 'Something bad happened ' + error
}));

Categories