IONIC 3 CORS ISSUE - json

I am having a CORS issue with Ionic 3 when attempting to make GET calls to an API. I am using Ionic local server, running ionic serve in the command line for live server.
Error No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not
allowed access.
I tried updating ionic.config.json with proxy setting but that does not seem to be working..
{
"name": "projectLeagueApp",
"app_id": "47182aef",
"type": "ionic-angular",
"integrations": {
"cordova": {}
},
"proxies": [
{
"path":"/games",
"proxyUrl": "https://api-2445582011268.apicast.io/games/"
}
]
}
My Data Service
import { Injectable } from '#angular/core';
import { Http, Headers, RequestOptions } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class DataProvider {
headers = new Headers({'user-key': '1234567890123'});
options = new RequestOptions ({headers: this.headers});
limit: number = 50;
constructor(public http: Http) {
console.log('Hello DataProvider Provider');
}
getGames(genre, offset_num) {
let genre_id = genre;
let offset = offset_num;
return this.http.get('https://api-2445582011268.apicast.io/games/?fields=name,release_dates,screenshots&limit='+this.limit+'&offset='+offset+'&order=release_dates.date:desc&filter[genres][eq]='+genre_id+'&filter[screenshots][exists]', this.options)
}
}
I am trying to make calls to this api
Request Url
https://api-2445582011268.apicast.io
HEADERS
Key Value
user-key YOUR_KEY
Accept application/json
Primary Question
My calls are failing. How do I create proxy for this issue?

To fix this issue, please change the following lines
ionic.config.json
{
"name": "projectLeagueApp",
"app_id": "47182aef",
"type": "ionic-angular",
"integrations": {
"cordova": {}
},
"proxies": [
{
"path":"/games",
"proxyUrl": "https://api-2445582011268.apicast.io/games"
}
]
}
You have to remove the " / " which is at the end of of "proxyUrl".
My Data Service
return this.http.get('/games/?fields=name,release_dates,screenshots&limit='+this.limit+'&offset='+offset+'&order=release_dates.date:desc&filter[genres][eq]='+genre_id+'&filter[screenshots][exists]', this.options)
In the http call, the url should begin with '/games'. '/games' because ionic will proxy http://localhost:<port>/games to https://api-2445582011268.apicast.io/games
Please use the above method for external GET and POST calls in your application.
Thank you.

If you wan to use for testing in Chrome just install chrome extension
Allow control origin
Quick and easy way

To test in development environment, you can run Google Chrome in disable-web-security mode.
Steps to follow (On Windows)
Press Windows Key + R to open Run window.
Enter/input following command and press Enter key.
chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
Steps to follow (On Ubuntu)
Kill all the chrome.exe instances before you run/execute it.
chromium-browser --disable-web-security --user-data-dir="[some directory here]"
Before Chrome 48
chromium-browser --disable-web-security
Steps to follow (On Mac)
Run following command in terminal.
open -n -a "Google Chrome" --args --user-data-dir=/tmp/temp_chrome_user_data_dir http://localhost:8100/ --disable-web-security

the proxy functionality expects that you're referencing the local server. in your GET request, you're still pointed at the remote API. If you change your code to this.http.get('/games/...' it should start to function as the request will go to http://localhost:8100/games..., which the "proxy" option will catch and pass on to the URL you've provided.
You may also only need to put https://api-2445582011268.apicast.io in the proxyUrl field. I think the rest of the path is passthrough.

My CORS issue got FIXED when I updated Android System Webview from the play store.
I tried Cordova-Advance-HTTP Plugin but my PUT Request was not working with Cordova-Advance-HTTP plugin.
After Updating Android System Webview I used HTTP Client plugin which I was using before. Updating Android System Webview helped me in CORS issue

```
export function getAuthHttp(http: Http, options: RequestOptions) {
console.log("token",storage.get('id_token'));
return new AuthHttp(new AuthConfig({
headerName: 'Authorization',
headerPrefix: 'bearer',
tokenName: 'id_token',
tokenGetter: (() => storage.get('id_token')),
noJwtError: true,
//globalHeaders: [{'Accept': 'application/json'}],
globalHeaders: [{'Content-Type':'application/json'},{"Access-Control-Allow-Origin": "*"}],
}), http, options);
}
```

You can handle the CORS when debugging in browser by using CORS extension or by disabling the security of Chrome.
But you need to handle the CORS when you debug in app on the server side, I was consuming woo-commerce API ,so i edited it as follows->
1.Plugins->editor->woocomerceapi
right after
<?php**
header(“Access-Control-Allow-Origin: *”);
2.Update File

Related

How to prevent Vercel routing to not finding the page

I am building a project using NextJs and Vercel, but, when the users try to access a new page or route, the Vercel gives them the 404 error.
In other projects, I used Netlify as router and this error was fixed using the netlify.toml config file, but, I am not able to do the same using the vercel.json file.
Can you guys help me to turn this file:
netlify.toml
[[redirects]]
from = "/*"
to = "/index.html"
status = 200
Into a vercel.json config file?
I was trying with this settings:
vercel.json
{
"rewrites": [{ "source": "/(.*)", "destination": "/index.html"}]
}
But it did not solved my issue.
A workaround is to use a catch all route that immediately redirects to the index page. For example:
// [...404].jsx
export default function Page() {
return null;
}
export function getServerSideProps() {
return {
redirect: {
destination: '/',
permanent: false,
},
};
}

sveltekit routes not working when deployed to server

Here's my svelte.config.js and I'm using adapter-static :
const config = {
kit: {
adapter: adapter({
// default options are shown
pages: '../backend/build',
assets: '../backend/build',
fallback: null,
precompress: false,
}),
alias: {},
appDir: '_app',
browser: {
hydrate: true,
router: true,
},
files: {
assets: 'static',
hooks: 'src/hooks',
lib: 'src/lib',
params: 'src/params',
routes: 'src/routes',
serviceWorker: 'src/service-worker',
template: 'src/app.html',
},
floc: false,
methodOverride: {
parameter: '_method',
allowed: [],
},
paths: {
assets: '',
base: '',
},
trailingSlash: 'always',
vite: {
server: {
proxy: {
'/api': 'http://localhost:5555',
},
},
},
},
preprocess: null,};
From the backend (Go lang) I'm serving build directory & index.html file. The homepage works fine but whenever I click on any route, it sends get request to the server instead of redirecting in the app itself.
Here's the go code to serve from backend:
router := gin.Default()
router.StaticFile("/", "./build/index.html")
router.StaticFS("/_app", http.Dir("build/_app"))
I have also tried with the following code:
router.NoRoute(func(c *gin.Context) {
path := c.Request.URL.Path
c.File("./build/index.html")
})
Note: Things work fine when I run npm run preview.
The adapter-static has two distinct modes of operation: SPA and prerendering. When there are several routes, both the npm run dev and npm run preview works as intended, but once built, the static routing falls to the web server, in your case, the Go framework, but the same happens with any other static server (I have tested also Nginx and Apache).
I found a workaround to avoid converting the site to a SPA: Installing a url rewrite mechanism as a middleware in order to add the .html extension that the static server is expecting in the compiled site. In my case, I used Go Fiber github.com/gofiber/rewrite/v2 and it worked as intended (the same behavior as when using npm run dev)
For Nginx static server the solution is the same url rewrite and it could be used as explained here: https://www.codesmite.com/article/clean-url-rewrites-using-nginx
The homepage works fine but whenever I click on any route, it sends get request to the server instead of redirecting in the app itself
SvelteKit users internal router, or $app/navigator for links only if it detects a link to be the same domain as the current page. Likely your web server is misconfigured and there is a mismatch of domain somewhere in
The web browser address bar
Web server configuration
However, the question do not contain these details and is thus unanswerable "why" and how to fix it.

Is there anyway to have TestCafe Studio select the client certificate when the browser is launched?

I would like to automate a web page using TestCafe Studio. However, every time the web page is launched you have to select a certificate to validate yourself before the page is loaded. Is there anyway that TestCafe Studio can select the certificate? Any help would be greatly appreciated.
You can authenticate a user with a client certificate using the Request Hook.
Create a RequestHook like:
const target = /https:\/\/my\.secure\.host/
export class MyRequestHook extends RequestHook {
constructor() {
super(target)
}
onRequest(event) {
// add keys to request
Object.assign(event.requestOptions, {
...keys
})
}
onResponse() {}
}
where keys is
const keys = {
key: fs.readFileSync(USER_KEY),
cert: fs.readFileSync(USER_CRT),
ca: fs.readFileSync(CA_CRT)
}
the constants USER_KEY, USER_CRT, CA_CRT are paths to the PEM formatted keys/certs.

Vue Axios CORS policy: No 'Access-Control-Allow-Origin'

I build an app use vue and codeigniter, but I have a problem when I try to get api, I got this error on console
Access to XMLHttpRequest at 'http://localhost:8888/project/login'
from origin 'http://localhost:8080' has been blocked by CORS policy:
Request header field access-control-allow-origin is not allowed
by Access-Control-Allow-Headers in preflight response.
I have been try like this on front-end (main.js)
axios.defaults.headers.common['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
and this on backend (controller)
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
and vue login method
this.axios.post('http://localhost:8888/project/login', this.data, {
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PATCH, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Origin, Content-Type, X-Auth-Token"
}
}).then(res => {
console.log(res);
}).catch(err => {
console.log(err.response);
});
I've searched and tried in stackoverflow but does not work, how I can solve it? thank you so much for your help
CORS is the server telling the client what kind of HTTP requests the client is allowed to make. Anytime you see a Access-Control-Allow-* header, those should be sent by the server, NOT the client. The server is "allowing" the client to send certain headers. It doesn't make sense for the client to give itself permission. So remove these headers from your frontend code.
axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
this.axios.post('http://localhost:8888/project/login', this.data, {
headers: {
// remove headers
}
}).then(res => {
console.log(res);
}).catch(err => {
console.log(err.response);
});
For example, imagine your backend set this cors header.
header("Access-Control-Allow-Methods: GET");
That means a client from a different origin is only allowed to send GET requests, so axios.get would work, axios.post would fail, axios.delete would fail, etc.
This may occur you are trying call another host for ex- You Vue app is running on localhost:8080 but your backend API is running on http://localhost:8888
In this situation axios request looking for this localhost:8080/project/login instead of this http://localhost:8888/project/login
To solve this issue you need to create proxy in your vue app
Follow this instruction Create js file vue.config.js or webpack.config.js if you haven't it yet inside root folder
then include below
module.exports = {
devServer: {
proxy: 'https://localhost:8888'
} }
If you need multiple backends use below
module.exports = {
devServer: {
proxy: {
'/V1': {
target: 'http://localhost:8888',
changeOrigin: true,
pathRewrite: {
'^/V1': ''
}
},
'/V2': {
target: 'https://loclhost:4437',
changeOrigin: true,
pathRewrite: {
'^/V2': ''
}
},
}
}
If you select the second one in front of the end point use the V1 or V2
ex - your end point is /project/login before it use V1/project/login or V2/project/login
as per the host
Check this Vue project - https://github.com/ashanoulu/helsinki_city_bike_app/tree/main/Front_End/app-view
Version - Vue3
For more details visit - Vue official documentation
in my case
curl && postman works but not vue axios.post
Access to XMLHttpRequest at 'http://%%%%:9200/lead/_search' from origin 'http://%%%%.local' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
So, the issue is on vue side not the server!
The server response contains "access-control-allow-origin: *" header
I had the same problem even everything was fine on the server side..
The solution to the problem was that API link I hit was missing the slash (/) at the end so that produced CORS error.
in my case adding this in my php backend API function it worked
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS, post, get');
header("Access-Control-Max-Age", "3600");
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header("Access-Control-Allow-Credentials", "true");
You may try :
At the backend,
npm install cors
then, at the backend app.js , add the following,
const cors = require('cors')
app.use(cors({
origin: ['http://localhost:8082'],
}))
Hopefully, It may help.
Dev Proxy is your solution
With DevProxy you define a specific path, or a wildcard (non static) that Node (the server runs vue-cli dev server) will route traffic to.
Once defined (a single entry in vue.config.js), you call your api with the same URI as your UI (same host and port) and Vue is redirecting the request to the API server while providing the proper CORS headers.
look more at https://cli.vuejs.org/config/#devserver-proxy
I'm building an app in Vue.js and added global headers in the main.js file
Example:
axios.defaults.headers.get['header-name'] = 'value'
For handling CORS issues you may now have to make changes on the client side, it is not just a server issue.
Chrome has a few plugins: https://chrome.google.com/webstore/search/cors?hl=en
for some cases, it is not vue issue. sometimes it's back-end issue.. in my case I've made API in nest JS, and I didn't enable CORS = true.. That's why I am getting CORS policy error.
in my case, the API would return CORS policy, but the problem lied with my url.
my calls were like "https://api.com//call", that extra slash was causing the problem.
changing the url to "https://api.com/call" fixed the error.

DART lang reading JSON file saved in the client, i.e. without using a server

I'm trying to read data from JSON file, using the blow code:
void makeRequest(Event e){
var path='json/config.json';
var httpRequest= new HttpRequest();
httpRequest
..open('GET', path)
..onLoadEnd.listen((e)=>requestComplete(httpRequest))
..send('');
}
this worked very well when the app run as http:// .../ index.html, but gave the below error when trying to open it as file:///.../index.html
Exception: NetworkError: Failed to load 'file:///D:/DartApp/web/json/config.json'. main.dart:53makeRequest main.dart:53<anonymous closure>
Is there another way, other than httpRequest that can read JSON file from client side!
I understand I've 3 options, 2 of them only can use HttPRequest, which are:
saving the file of the server, and reading it from the server => can use HttpRequesit
saving the file on the server, and reading it from the client => can use HttpRequesit
saving the file on the client, and reading it from the client itself => CAN NOT use HTTPRequest
I'm searching for the way to do the 3rd option, which is like making off-line Android App using webview, or making off-line Chrome packaged app, i.e I do not want to use a server at all. thanks
thanks
If all you need is the data in the json file, you can just include that data in your .dart files (as a Map variable/constant, for example).
Map config = {
"displayName": "My Display Name",
"anotherProperty": 42,
"complexProperty": {
"value_1": "actual value",
"value_2": "another value"
}
};
If you need the actual json, you can put in a String. Something like:
const configJson = '''
{ "displayName": "My Display Name",
"anotherProperty": 42,
"complexProperty": {
"value_1": "actual value",
"value_2": "another value"
}
}
''';
The json data can be in a separate .dart file, which can be included as part of the same library (through part of ...), or imported (import 'package:mypackage/json.dart';).
If you're looking for something that you can change and the changes are persisted, you're going to need to use some sort of offline storage, which can be web storage if you're running in a browser. You can use the approach above to define inital config data, store it in web storage, and from then on read and edit it from there.
[Previous answer below, before original question was edited.]
Sorry, read "client side", thought "server side". My mistake.
If by "client side" you mean "running in a browser", and you're trying to access a json file which is on the server, then no, there isn't any other way, other than an http request. In fact, that's the only way to read any file on the server, not just json ones. (Well, I guess you could open a WebSocket and stream the content, but that doesn't seem to be a solution you're looking for.)
[Old solution below, before my mistake (server vs client) was pointed out.]
Try:
// THIS DOESN'T WORK IN A BROWSER ENVIRONMENT (aka client side)
import 'dart:io';
import 'dart:convert';
// ...
new File('json/config.json')
.readAsString()
.then((fileContents) => json.decode(fileContents))
.then((jsonData) {
// do whatever you want with the data
});
This poor example works fine in the chrome dev editor dart web app example.
Using HttpRequest.getString works fine with filename and path.
Chris has a good write for json web service stuff at
https://www.dartlang.org/articles/json-web-service/
import 'dart:html';
import 'dart:convert';
void main() {
HttpRequest.getString('json/config.json').then((myjson) {
Map data = JSON.decode(myjson);
var version = data["version"];
var element = new DivElement();
element.text = "version = $version";
document.body.children.add(element);
});
}