No 'Access-Control-Allow-Origin' header when launch ajax in vue component under electron-vue dev envrironment - vue.js

Following https://github.com/SimulatedGREG/electron-vue, i run yarn run dev and make a minor change to see how it works.
In electron vue application, i have launch an ajax request in vue component created hook function,
created: function () {
let self = this
this.$http.get('http://example.com/api/hwid/383').then(
function (resp) {
self.title = resp.title
}
)
}
In the vue-electron dev tool, there are following error in the console:
XMLHttpRequest cannot load http://example.com/api/hwid/383. No 'Access- Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9080' is therefore not allowed access.
How to solve that?
Must i set the cross domain in the server side?

Yes, you should add Access-Control-Allow-Origin for localhost on the server side.
Since it's only a browser policy, you eventually can write your own (proxy) server which will get http://example.com/api/hwid/383 data. Then you will request data through your server without any issues.

Related

How to stop 'CORS missing allow origin error' when deploying Express application using Serverless Component?

When my React frontend calls my Typescript Express REST API (hosted on API Gateway using Serverless Components), I get the following error:
Access to XMLHttpRequest at 'https://randomId.execute-api.ap-southeast-2.amazonaws.com/userLoginSignup' from origin 'https://www.tueshey.com' 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.
My app.ts CORS config is like this (for reference, here's my whole file):
...
const app = express();
// CORS
const allowlist = ['https://www.tueshey.com'];
const options: cors.CorsOptions = {
origin: allowlist,
};
app.use(cors(options));
...
When I inspect the request locally, there is an OPTIONS request that returns first that includes the Allow Access Origin header but not when I deploy it. It is working correctly locally.
you will have to enable CORS on API Gateway as well. When click on the resource endpoint on API Gateway, on actions there is Enable CORS. That will add Options method also for your resource. If you want some customization you will have to add OPTIONS method manually

Access to fetch at * from origin * has been blocked by CORS policy, even though CORS policy explicitly allows it

I am performing a graphql query from my client to my server and am getting the following error in the browser:
Access to fetch at 'https://my-server.com/graphql' from origin 'https://my-client.com' 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.
I once got this same error in the past which is why I added the following to the express middleware on the server which solved it:
const app = express();
app.use(cors({
origin: ['http://localhost:3000', 'https://studio.apollographql.com', "https://my-client.com"],
credentials: true
}))
However without any changes that I can reasonably trace back to this issue the error is occurring again. The strange thing if I run the client and server on my local machine (on localhost:3000 and localhost:4000 respectively) the error does not happen.
Edit:
On the client I use a library called GraphQL Code Generator to generate hooks which execute the relevant queries. One of them is for instance this one:
export function useUsersQuery(baseOptions?: Apollo.QueryHookOptions<UsersQuery, UsersQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<UsersQuery, UsersQueryVariables>(UsersDocument, options);
}
And to execute the query: const { data, loading, error } = useUsersQuery()
I am using the following package versions
apollo-server-express#3.11.1
express#4.18.2
cors#2.8.5

Nuxt 3 $fetch method doesn't work with golang servers?

UPD: you can check this yourself: https://github.com/Rusinas/nuxt-fetch-bug
I know I know this sounds stupid as hell and server language has nothing to do with such problems, but hear me out.
I am trying to load data from my local server using $fetch() (or useFetch, no difference), but I get this error:
FetchError: fetch failed ()
No any other details provided. Server is running using Golang/Fiber. When I am trying to load the same endpoint via Postman, everything is OK:
But when I try to load the SAME endpoint in my nuxt 3 application:
I get this:
But my golang server logging this as success:
The more weird thing about all this is that if I run my nodejs version of the exact same server (or any other random API), I don't get any error.
I am pretty sure that my server working 100% correct, but maybe I lost some header or something, which express put automatically? Here is my response headers:
I also checked nodejs response headers:
Doesn't seem like problem is there.
I have no idea what is happening and I don't know other methods to retrieve async data on server side in nuxt js. I have installed axios, but it throws random errors and works on client side for some reason, which makes using nuxt meaningless. However, axios can call this endpoint and returns my data, but only in browser (despite I call it in setup function without any hooks). I am thinking to switch career now
The problem was that fetch() didn't reconize localhost:9000 for some
reason, but when I changed BASE_URL to 127.0.0.1:9000 it started to
work
I had the same error: FetchError: fetch failed ()
Changing localhost in the url to 127.0.0.1 worked for me.
Writing as a separate answer because some might not find it in the comments.
First I think you are using $fetch in a wrong way, as I've seen Nuxt uses fetch for example:
const data = await fetch(endpoint, {
method: "GET",
mode: "cors"
})
.then(resp => resp.json())
And for the server, just enable CORS header on the response, like this:
// you can replace the asterisk with the clients you want.
c.Append("Access-Control-Allow-Origin", "*")
hope I helped :)

Laravel Access to XMLHttpRequest error how to fix

I have a Laravel 7 application and I'm trying to access an external URL in a Bootstrap model window. When I use the below jQuery function, on button click, I want to load the model and show the external website.
$('#myModal').on('show.bs.modal', function (e) {
$(this).find('.modal-body').load('http://***.com');
});
I get the bellow error.
Access to XMLHttpRequest at 'http://****' from origin 'http://****'
has been blocked by CORS policy: Response to
preflight request doesn't pass access control check: Redirect is
not allowed for a preflight request.
I have searched and found one solution to use middleware. I created the middleware file in app\http\Middleware\Cors.php.
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods',
'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers',
'Accept,Authorization,Content-Type');
}
After that I have added the following in app\http\Kernel.php.
protected $middleware = [
....
...
\App\Http\Middleware\Cors::class,
];
But I still get the same error. How can I fix this error?
Laravel 7 has been released in March and provides built-in support for CORS so developers don't need to use third-party packages to enable CORS in their Laravel apps.
You can use config/cors.php file for your cors settings.
For more details please follow the link - https://www.techiediaries.com/laravel/laravel-7-6-cors-example-and-tutorial/
Since you didn't explicitly mention it I'll assume you didn't do this:
you have to enable CORS for every route you want to use it with.
According to:
https://github.com/fruitcake/laravel-cors
There can be CORS on Both side on
1 API side at external URL. ( this you cannot change)
2 At your bootstrap Laravel application.( this you can change)
$('#myModal').on('show.bs.modal', function (e) {
$(this).find('.modal-body').load('http://***.com');
});
This is just a Jquery code. Can you convert this code to some server side language like php?
Remember CORS can be overridden by server side code.

How to load JSON in Vue CLI without CORS error

I have a Vue.js project wrapped in an Electron app. From one of my components (src/components/MoviesTable.vue), I'm making an axios call to a local JSON file (public/data/multimedia.json), like this:
axios.get('./data/multimedia.json').then(res => {
this.movies = res.data.movies;
})
When I run npm run serve to serve the Vue app, I experience no issues. However, when I build the Electron app, I receive the error:
Access to XMLHttpRequest at '.../multimedia-index-app/dist/data/multimedia.json' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
I've tried using proxies to no avail. I know that similar questions about CORS have been asked on SO, which offer different solutions, but I'm a noob, and I need clearer instructions than the ones that I've come across.
Please let me know if you require more information. Any help in resolving this problem would be greatly appreciated.
Thanks in advance.
If the JSON file should be bundled with the app, you don't need Axios, you can have Webpack load it:
import movies from './data/multimedia.json';
And use it in the component:
export default {
data() {
return {
movies
}
}
}