Rocket.chat - login via Rest API - 401 - xmlhttprequest

I'm trying to login to my Rocket.chat app on localhost via API.
When I'm sending POST to http://localhost:3000/api/login with data: {"user":"myusername","password":"mypassword"}
I'm getting response 401 with status error, no matter if used xhr request, axios or jquery ajax.
BUT when I send the same data with python virtualenv or curl, the response is 200 and status success.
What am I doing wrong? Why POST fails when sending with javascript and passes when sending with python or curl?
var xhr = new XMLHttpRequest();
xhr.open("POST", 'http://localhost:3000/api/login/', true);
xhr.send(JSON.stringify({
user: "myusername",
password: "mypassword"
}));
// result: {status: "error", message: "Unauthorized"}
I'm sending login request with no header, because:
xhr.setRequestHeader('Content-Type', 'application/json');
returns 500
Here are request details from Chrome:

You are running rocket chat on a domain which is different from the domain from which you are making ajax request. The domain and port from which you make ajax request should be same as the domain and port of the destination url. This is because of a security feature in web browsers called Cross Origin Resource Sharing (CORS). See https://en.wikipedia.org/wiki/Cross-origin_resource_sharing.
To fix this error your web server needs to allow requests from other domains.

try this Code
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
xmlhttp.open("POST","http://localhost:3000/api/login/");
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF- 8");xmlhttp.send(JSON.stringify({name:"myusername", time:"mypassword"}));

Related

Ionic 6 API REST post method headers

I'm trying to make a API REST Request but i can't connect with the api, i'd trying different options but i could do it.
This is my ts
post(emplead2){
let data = {
"LastName": this.LastName
}
this.proveedor.addStudent(data)
.subscribe(
(data)=>{this.empleados = data;},
(error)=>{console.log(error);}
)
}
this is my service
addStudent(data): Observable<any> {
const headers = new HttpHeaders().append('Content-Type','application/json');
const body = 'hola';
console.log(body)
console.log(headers)
return this.http.post('APIURL',body,{headers: headers});
}
this is the error
Access to XMLHttpRequest at 'MYAPIURL' from origin 'http://localhost:8100' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
The problem here is not from your ionic application or how you are sending the POST request. What is basically happening is that your http request is being blocked by CORS policy for security reasons. You can check here what exactly is CORS policy and why it is blocking your request.
Fixing this depends on the language/framework you built the API with, but what you need to do is allow your ionic application's base url (http://localhost:8100) to access the API and bypass the CORS policy.

get CORS problem when ty to get a token in keycloak with vuejs and axios

I trying to access one keycloak with axios in my vuejs app, but I receive the cors error, can someone help me please? (If I make a post from POSTMAN to my keycloak works fine)
I using this code:
const params = new URLSearchParams();
params.append("grant_type", "password");
params.append("client_id", "notas-front");
params.append("username", usuario.value);
params.append("password", password.value);
console.log(params);
const config = {
// withCredentials: true,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
};
axios.defaults.headers.common["Access-Control-Allow-Origin"] =
"http://localhost:8080";
axios
.post(
"http://localhost:8082/auth/realms/lumera/protocol/openid-connect/token",
params,
config
)
.then((response) => {
console.log(response);
});
and get this error:
but when I look the request I can't find the error:
the OPTIONS returns 200
but the POST dont
Postman doesn't care about Same Origin Policy, browser do. That's why your request is working in Postman but not in the browser.
Access-Control-Allow-Origin is a response header, you can't set it on the client request. And as you can see from the OPTIONS response headers your server is returning: Access-Control-Allow-Origin: http://localhost:8080
In a development environment the best way to solve this is setting a proxy in your vue configuration. Otherwise you should configure the server to allow requests from localhost:8080
Configure Web Origins properly in the Keycloak notas-front client config.

Axios not sending custom header during options request

I have a running Vue.js application that request to the server.
My client-side application is running on e.g. cms.abc.com and the server in ApiGee running on this dns server.abc.com
The request code using axios is
const headers = {
'x-api-key': 'xxxxx123123'
}
return axios({
method: get,
url: 'server.abc.com/items',
headers: headers
}).then(response => {
console.log(respnose.data)
})
When I check the browser network I'm getting status 401 Unauthorized during OPTIONS request.
The APIgee CORS has been enabled, but when I check the logs from the ApiGee the value for x-api-key is missing.
I'm also not sure why my client side application is still sending OPTIONS request. I'm expecting that it should skip the CORS since the client and the server are having the same origin. which is abc.com

Routing error in vue.js - Access to XMLHttpRequest at

i'm new in vue.js
i wrote an method for posting data and get page address (get and post) like this
updateCategory() {
this.$eventBus.$emit("loadingStatus", true);
this.$axios.get("http://rimonbd.com/tutorial/api/update-category", this.clickedCategory)
.then(res => {
this.$eventBus.$emit("loadingStatus", false);
this.showingAddModal = false;
if (res.data.error) {
this.$iziToast.error({
title: 'Error',
message: res.data.message,
});
} else {
this.$iziToast.success({
title:'Succes',
message:res.data.message,
});
and i got this error :'(
Access to XMLHttpRequest at 'http://rimonbd.com/tutorial/api/get-category' from origin 'http://localhost:8080' 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.
how should i fix that ?
The website you're trying to request data doesn't allow requests from different domains. You're on localhost:8080 requesting data from and external website.
You can try
Use local data to test your project
Deploy your project under the same domain of your data.
Read more about CORS https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
Try a hack, only for tests, don't put this in production https://cors-anywhere.herokuapp.com/
example:
this.$axios.get("https://cors-anywhere.herokuapp.com/http://rimonbd.com/tutorial/api/update-category", this.clickedCategory)

node-bigcommerce Get and Post Routes

I'm using the npm package, 'node bigcommerce', and I have all my API's setup but whenever I try to make a GET route, the error, Error: Request returned error code: 404 and body: The route is not found, check the URL, shows up. I don't know how or where to specify the url to find. Also, I have the same problem with POST Routes. The code is here. Thanks ahead!
var express = require('express'),
BigCommerce = require('node-bigcommerce');
var bigCommerce = new BigCommerce({
clientId: '* Client ID *',
secret: '* Secret *',
callback: 'https://store-xxi13.mybigcommerce.com',
responceType: 'json',
accessToken: '* Access Token *',
storeHash: 'xxi13'
});
bigCommerce.get('/happy', (data) =>{
console.log(data);
});
The path supplied in your get request, '/happy' is not a BigCommerce API endpoint--that's why you're getting a 404 not found. If you made a request to /products for example, it should work to pull product data.
Also, the callback would usually be a path on your app, not the store URL. For example, callback: 'https://myapplication.com/auth', would be the path on your app where you want the BigCommerce auth service to send your temporary code and Oauth token during the installation flow:
https://developer.bigcommerce.com/api/#app-installation-and-update-sequence
You can find examples of configuring the client and making requests in the README for the node-bigcommerce client:
https://github.com/getconversio/node-bigcommerce