Ionic cors issues - angularjs

I am trying to do authentication in ionic with laravel in the backend. When I was testing it with postman authentication works, and I am getting back a token, but I have cors issues when I am trying to do authentication form ionic, when I do ionic serve. I have tried to set it up as suggested here.
This is my ionic.project file:
{
"name": "myApp",
"app_id": "",
"gulpStartupTasks": [
"sass",
"watch"
],
"watchPatterns": [
"www/**/*",
"!www/lib/**/*"
],
"proxies": [
{
"path": "/api/*",
"proxyUrl": "http://myBackend.app/api"
}
]
}
My gulpfile:
var replace = require('replace');
var replaceFiles = ['./www/js/app.js'];
gulp.task('add-proxy', function() {
return replace({
regex: "http://myBackend.app/api",
replacement: "http://localhost:8100/api",
paths: replaceFiles,
recursive: false,
silent: false,
});
});
gulp.task('remove-proxy', function() {
return replace({
regex: "http://localhost:8100/api",
replacement: "http://myBackend.app/api",
paths: replaceFiles,
recursive: false,
silent: false,
});
});
So when I try to authenticate user, on a failed attempt I get a return from my backend:
POST http://myBackend.app/api/authenticate 401 (Unauthorized)
And when I send the right credentials I get:
XMLHttpRequest cannot load http://localhost:8000/api/authenticate.
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:8100' is therefore not allowed
access. The response had HTTP status code 500.

Related

Npm package #paypal/react-paypal-js gives cors error

I am following this blog:
react and paypal integration
When I run this code:
actions.order
.create({
purchase_units: [
{
description: "Sunflower",
amount: {
currency_code: "USD",
value: 20,
},
},
],
// not needed if a shipping address is actually needed
application_context: {
shipping_preference: "NO_SHIPPING",
},
})
.then((orderID) => {
setOrderID(orderID);
return orderID;
});
Pop up shows and when I try to login
I get the following error:
Access to XMLHttpRequest at 'https://c.paypal.com/v1/r/d/b/pa' from origin 'https://c.sandbox.paypal.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
I am trying to log in from the same account that API is created from

Sails 1.4.0 CSRF Token sent from React App getting rejected 403

for the last three days I got stuck at this problem and it is getting very frustrating. I don't know what else to try.
I am running a Sails app on localhost:1337 and a create-react-app on localhost:3000.
I enabled csrf on the backend and followed the sails documentation to implement it.
I have created the route
'GET /grant-csrf-token': { action: 'security/grant-csrf-token' } and it works fine, I get the token. If I use postman the token is accpeted and my login form works.
In React however, I receive the token but I get 403 Forbidden error when I submit the post request to login.
useEffect(async () => {
let csrfToken;
try {
let csrfTokenRequest = await Axios.get(
`${state.serverUrl}/grant-csrf-token`
);
csrfToken = csrfTokenRequest.data["_csrf"];
dispatch({
type: "csrf",
value: csrfToken,
});
} catch (err) {
dispatch({
type: "flashMessage",
value: "There was an error.",
});
}
}, []);
I tried various ways to send the token with my post request:
await Axios.post(
`${appState.serverUrl}/login`,
{
emailAddress,
password,
_csrf: appState.csrf,
},
{ withCredentials: true }
);
I also tried setting it as a default header like so:
Axios.defaults.headers.post["X-CSRF-Token"] = appState.csrf;
and set cors allowRequestHeaders parameter to allowRequestHeaders: 'content-type, X-CSRF-Token',
I also tried sending it as a query parameter
`/login?_csrf=${encodeURIComponent(appState.csrf)}`
I also tried various cors settings inside Sails, currently it is setup like so:
cors: {
allRoutes: true,
allowOrigins: [
'http://localhost:3000',
],
allowCredentials: true
}
So just to clarify once again:
The /grant-csrf-token route works fine. I am receiving the token
It works in Postman
In React I get 403 error
Could you try something like that:
Send the csrf in header and allow Sails to process the request header.
// config/security.js
cors: {
allRoutes: true,
allowOrigins: ['http://localhost:3000'],
allowCredentials: true,
allowRequestHeaders: ['content-type', 'x-csrf-token', 'authorization'],
},

How to send request to an API on remote server via webpack devlopment server using axios

I want to fetch some data from my remote server supporting REST API.
I am using axios and web-dev-server. My frontend is sending request and I have used both firefox and chrome to open my frontend.
However every time I tries to make request I encounter cors error.
Also I don't want to make any changes on my server.
The firefox and chrome are sending this header.
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language :en-US,en;q=0.5
Connection:keep-alive
Host:my.ip.to.host:port
Origin:http://localhost:3000
Referer:http://localhost:3000/login
User-Agent:Mozilla/5.0 (X11; Ubuntu; Linu…) Gecko/20100101 Firefox/67.0
I have tried to run my simple request code on an online platform without web-dev-server and there it runs perfectly fine.
Here is my code
//********** my request*********
return axios
.get('http://my.ip.to.host:port/api/User/login', {
headers: {
Accept: '/'
}
})
.then(function(response) {
console.log(response);
return 'user';
})
.catch(function(error) {
console.log(error);
return 'err';
});
//*****************************
//*****webpack.config.js********
var HtmlWebpackPlugin = require('html-webpack-plugin');
require('babel-polyfill');
module.exports = {
mode: 'development',
entry: [ 'babel-polyfill', './src' ],
resolve: {
extensions: [ '.js', '.jsx' ]
},
module: {
rules: [
{
test: /.jsx?$/,
loader: 'babel-loader'
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
})
],
devServer: {
historyApiFallback: true,
port: 3000
},
externals: {
// global app config object
config: JSON.stringify({
apiUrl: 'http://localhost:4000',
checkLogin: 'http://my.ip.to.host:port/api/User/login'
})
}
};
Here is the error I am getting.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://my.ip.to.host:port/api/User/login. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).`enter code here`
You need to set withCredentials as true in axios config. Cors Setting
let HttpInterceptor = axios.create({
headers: {
Accept: "*/*"
}
});
HttpInterceptor.interceptors.request.use(
function(config) {
config.withCredentials = true; // To enable CORS
return config;
},
function(error) {
return promise.reject(error);
}
);
//********** Your request*********
return HttpInterceptor
.get('http://my.ip.to.host:port/api/User/login')
.then(function(response) {
console.log(response);
return 'user';
})
.catch(function(error) {
console.log(error);
return 'err';
});
Here Google has explained the cors(Cross-origin requests) very nicely.
I have worked around this by hosting a proxy server(on the same local server where I am hosting my client) and redirecting all my single page app request via that.
First of all, I created a proxy setting in devsever key of webpack config file, like this.
devServer: {
proxy: {
//abc is REST API request endpoint on my backend
'/abc': {
//target is where your proxy server is hosted
target: 'http://localhost:5000',
secure: 'false'
},
//xyz is REST API request endpoint on my backend
'/xyz': {
//target is where your proxy server is hosted
target: 'http://localhost:5000',
secure: 'false'
}
},......// rest of the setting
}
Then,
For a particular invocation of a action via my client I make request to my backend like this.
axios
.get('/startAppkey', { withCredentials: true })// withCredential enables passing of cookies and session id. If you dont want to creat session you can avoid this.
.then((response) => {
// do stuff with response
})
.catch(function() {
//do stuff
});
Our client is all set.
Now time for proxy server.
First install http-proxy-middleware,Like this.
sudo npm i --save http-proxy-middleware
//it is also avilable on yarn
then,
To setup proxy server here is few lines of code.
import * as express from 'express'; // using express to support my middleware
import * as proxy from 'http-proxy-middleware';
const app = express();
// the path /abc and /xyz should be same as you have declared in in webpack config file
app.use('/abc', proxy({ target: 'http://your/backend/api/endpoint'}));
app.use('/xyz', proxy({ target: 'http://your/backend/api/endpoint'}));
//that's it you are done here.

CORS error when calling post api directly from client

I have a post function that I have tested and is working perfectly. When I call it from my front end, I get the following error:
Access to XMLHttpRequest at 'https://sdigg5u4xb.execute-api.eu-west-1.amazonaws.com/prod/sites' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have tried disabling CORS and using different cognito identity pools to allow different permissions, but I still get the same error. When testing it in AWS, it is successful with no errors.
Here is where I am calling the API:
import { API } from "aws-amplify";
export default (async function submitSite(values) {
console.log(values);
return API.post("sites", "/sites", {
body: values
})
});
Here is where I am defining the function in my serverless.yml file:
createSite:
handler: CreateSite.main
events:
- http:
path: sites
method: post
cors: true
authorizer: aws_iam
I'd recommend you to check these.
Make sure you enable CORS in your API gateway as described here
Make sure your server less app have CORS enabled here.
Don't forget adding Access-Control-Allow-Origin response header to your function.
module.exports.hello = function(event, context, callback) {
const response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin" : "*", // Required for CORS support to work
"Access-Control-Allow-Credentials" : true // Required for cookies, authorization headers with HTTPS
},
body: JSON.stringify({ "message": "Hello World!" })
};
callback(null, response);

JSONP Unexpected Syntax Error (API doesn't support JSONP)

My function:
function getMarketData_() {
$http({
method: 'JSONP',
url: 'https://api.coinmarketcap.com/v2/ticker/',
}).then(function(response) {
console.log('ran');
}).catch(function(response) {
console.log('Error');
});
}
The Error:
Uncaught SyntaxError: Unexpected token :
The location of the error in the returned JSON:
The API doesn't support JSONP.
To test click: https://api.coinmarketcap.com/v2/ticker/?callback=test
An API that supports JSONP would send back something like:
test({
"data": {
"1": {
"id": 1,
"name": "Bitcoin",
"symbol": "BTC",
"website_slug": "bitcoin",
"rank": 1,
"circulating_supply": 17095362.0,
"total_supply": 17095362.0,
"max_supply": 21000000.0,
"quotes": {
"USD": {
"price": 6530.3,
"volume_24h": 4015800000.0,
"market_cap": 111637842469.0,
"percent_change_1h": -0.66,
"percent_change_24h": -2.31,
"percent_change_7d": -14.6
}
},
"last_updated": 1529097276
}
}
})
For more information, see Wikipedia - JSONP
See also Angular 1.6.3 is not allowing a JSONP request that was allowed in 1.5.8
The API supports CORS.
To test use:
https://www.test-cors.org/#?client_method=GET&client_credentials=false&server_url=https%3A%2F%2Fapi.coinmarketcap.com%2Fv2%2Fticker%2F&server_enable=true&server_status=200&server_credentials=false&server_tabs=remote
This question typically arises when a user attempts to use $http.get and gets:
XMLHttpRequest cannot load https://www.[website].com/ No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4300' is therefore not allowed access.
Then someone suggests $http.jsonp as the workaround. This only works if the API supports JSONP.
For more information, see
XMLHttpRequest cannot load https://www.[website].com/
Why does my JavaScript get a “No 'Access-Control-Allow-Origin' header is present on the requested resource” error when Postman does not?
How to enable CORS in AngularJs
How to use Cors anywhere to reverse proxy and add CORS headers

Resources