Is there anything I can do on the front end to read the response of a POST request to another domain? - cross-domain

I have a form
render() {
return (
<form onSubmit={this.handleSubmit}>
...
</form>
);
}
On submit I make a post request and print the response
handleSubmit(event) {
axios.post('https://.../oauth2/token', {
firstName: this.state.username,
password: this.state.password,
grant_type: password
})
.then(response => console.log(response))
event.preventDefault();
}
The printed response is
Failed to load https://.../oauth2/token: Response
to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:3000' is therefore not allowed
access. The response had HTTP status code 400.
I understand that this is supposed to protect against cookie abuse. But is there anything I can do on the front end to get the response? Maybe I can state in the request that I don't want to use any cookie rights.

No 'Access-Control-Allow-Origin' header is present on the requested resource
Right there tells me what's wrong. You've got a problem with CORS (Cross-Origin Resource Sharing). If you're using Chrome, you can use an extension for it.
For a permanent solution, you'll have to enable CORS on your host server. I can't offer much help with that, as I've got no idea what your backend looks like. You can try searching for " CORS". Personally, I just use the extension when I'm developing for simplicity's sake, but I'm only working on an AngularJS mobile app.

Related

Unable to make an API request to Twitter for .json return duo to CORS - Chrome extension- Manifest 3

I am trying to build a basic Chrome that shows an HTML page that I built on chrome://newtab. (Manifest 3).
Flow: My HTML file calls a local script file. The script file has a fetch function. The function calls the twitter 2.0 API with GET and a bearer auth to fetch all of the tweets made by a specific account. Account is recognized by id from twitter.
Results from the console:
"Access to fetch at 'https://api.twitter.com/2/users/44196397/tweets' from origin 'chrome-extension://epfgicoboagicldadiiggnmfgholpmna' 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."
The code I use:
fetch("https://api.twitter.com/2/users/44196397/tweets", {method: 'GET', headers : {Authorization : "Bearer ..🤫.."}}) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error));
Manifest includes: version:3, name, version, decription, author, chrome_url_overrides {newtab: index.html}, permissions [storage].
Tried:
no-cors header in fetch() - getting 401 error (according to Google, not supported on the blue side)
Postman - worked
curl commend on my PC - worked
Placing the script on an external server (I thought there is some sort of a security blockade for extensions, so then I could just extract the text) - CORS error also there. (On 000webhosting, no access to server config).
So from here on out, I'm stuck.I will highly appreciate any feedback!
Note: I'm new. Please ELI5, started programming with ChatGPT. Sorry if the post is overdetailed, didn't want to overlook something which might be important.
Cheers!

POST axios request blocked by fluidpay api

I'm trying to send a post request to this end point https://sandbox.fluidpay.com/api/token-auth and I'm getting this error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://sandbox.fluidpay.com/api/token-auth. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 405
When I send the request from Postman, it works. But when I try to send it using axios, I get the above error.
This is how I'm making the request using axios:
const request = await axios({method: "post", url: "https://sandbox.fluidpay.com/api/token-auth", data: {username: username, password: password}, withCredentials: false});
Shouldn't public API's be accessible to all domains?
EDIT
It looks CORS is disabled server side. If you don't control the server, you can't do much with a browser. The only way to solve the problem is using an API owned by yourself to proxy the request.
Read more here

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I am using nodejs server, express framework and fetch library to send request to another server which is in different domain. For one of my endpoint consider (localhost:8080/login) i am rendering ejs file when the user clicks login button i am sending a fetch request to an api (https:otherserver.com/login) different server which is in other domain. i am not able to send this request. I am getting this error :
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 404. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I am not sure how to handle this issue. please suggest some ideas or links which can solve this issue.
You can use cors middleware on your server.
Simplest way to use it is to add :
app.use(cors())
before all of your route handlers.
I found the solution for my problem. I am trying to explain what i understood as i am a beginner in server side and web development.
This was the problem i faced :
For one of my endpoint in my nodejs server, consider (localhost:8080/login) i am rendering ejs file when the user clicks login button in that ejs file, i am sending a fetch request to an api (https:otherserver.com/signin) of different server which is in other domain. i am not able to send this request. I was getting cors problem.
Cors problem was occuring because the server domain(my nodejs server) which rendered the ejs file and the other domain(https:otherserver.com/signin) to which i was making fetch request after clicking login button was different.
so solution was :
I need to make the fetch request first to the same domain(my nodejs server localhost:8080/api/signin). And then from this server i should call the api of other domain(https:otherserver.com/signin). By doing this we wont get any cors issue. Because the client side ejs file is requesting to the same server which has rendered the file. And then the server is bypassing the request to the other server.
code from client side javascript file. /api/signin is an endpoint in my local nodejs server and u can add the options:
options ={
method : 'POST',
headers : {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
body : JSON.stringify({
email_address : emailId,
password : pwd
})
};
fetch("/api/signin",options)
.then(function(res) {
console.log(res);
}).catch(function(error) {
console.log(error);
});
code from local nodejs server side:
express.use('/api/', function (req, res, next) {
var options = {
method : req.method,
headers :req.headers,
body : JSON.stringify(req.body)
};
fetch('https://otherserver.com'+req.path,options)
.then(response => {
return response.json();
}, error => { console.error(error)})
.then(function(json){
res.send(json);
})
.catch(function(error) {
res.send(error);
});
})
Hope this may help someone who is beginner in server development.

No 'Access-Control-Allow-Origin' header is present on the requested resource. - React/Node API

I'm trying to get passport authentication with twitter to work. My setup is as follows: React(with redux) frontend (create-react-app), Node (with express) API. Both are running on localhost (different ports).
User goes to /login and clicks on a button that dispatches a login action:
export function login() {
return dispatch => {
return axios.get('/api/auth/twitter')
.then(() => {})
}
}
The route on the server:
router.get('/twitter', passport.authenticate('twitter'));
And the route for the callback:
router.get('/twitter/callback', passport.authenticate('twitter', {failureRedirect: '/login'}), loginSuccess);
loginSuccess does nothing at the moment.
This is the full error I get:
XMLHttpRequest cannot load https://api.twitter.com/oauth/authenticate?oauth_token=fGVctgAAAAAA1y22AAABXah3t3o. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:3000' is therefore not allowed access.
I'm proxying requests from the react frontend (localhost:3000) to localhost:8080.
If I go into the network tab of the chrome devtools and select the response from the twitter api it looks like this:
If anyone knows how to get passport-twitter authentication to work with this kind of setup please let me know.
Sad news, Twitter won't let you to call its API client-side, you need a server in order to do that :(
Take a look at this Quora answer.

No 'Access-Control-Allow-Origin' header is present on the requested resource - VueJS

I'm developing a VueJS application which makes calls to an external API. When I do this:
this.$http.get(myAPIurl)
.then(response => {
return response.json();
})
.then(data => {
console.log(data);
});
I get these 2 errors in chrome console.
Refused to set unsafe header "Access-Control-Request-Method"
XMLHttpRequest cannot load http://xxxxxx Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access
How do I go about it?
If you are doing an XMLHttpRequest to a different domain than your page is on, your browser will block it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. A tutorial about how to achieve that is Using CORS.
When you are using postman they are not restricted by this policy. Quoted from Cross-Origin XMLHttpRequest:
Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.
To solve this, your external API server has to support cors request by setting following headers:
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
Edited
You can use format as jsonp, like it is being done in this codepen. Here is discussion on how to use jsonp with vue-resource, see sample code from this link:
this.$http.jsonp('https://api.instagram.com/v1/tags/' + this.hash + '/media/recent', {
client_id: 'xxxxxxxxxxxxxxxxxxxxxxxx'
}, function(data){
this.pictures = _map(data.data, this.transFormInstagramModelToLocalModel);
}, {
'jsonp': 'callback'
});
You can find discussions here also helpful.

Resources