How to use the website URL as base URL for Axios requests in a Nuxt.js app - axios

I have a webapp deployed and it's visitable via the domain url www.myapp.com.
Also I have a backend deployed that is called by a middleware calls via nuxt.config.js and serverMiddleware.
serverMiddleware: [
{ path: '/backend', handler: '~/api/backend.js' }
]
When deployed and using Axios out of the box the calls to the backend/middleware are done by http://localhost:3000 instead of www.myapp.com. Therefore CORS is being triggered and giving me this error in the console:
Access to XMLHttpRequest at 'http://localhost:3000/backend/packingplan/all?owner=123' from origin 'https://www.myapp.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.
So I did a little research and found out that I can override the base URL Axios uses. That way I can turn the http://localhost:3000 into www.myapp.com and avoid the CORS problem.
I am doing this like this:
create a Nuxt plugin ~/plugins/axios.js
add the following code
export default function (context) {
context.$axios.defaults.timeout = 15000
context.$axios.defaults.baseURL = context.$config.baseUrl || 'http://axios.plugin.failed'
}
add the plugin to the nuxt.config.js
plugins: [
'~/plugins/axios.js'
]
And this works. Now the CORS problem is solved.
BUT
It just works when I call my app with www.myapp.com. As soon as I open my webapp without the www then CORS is triggered again.
Access to XMLHttpRequest at 'https://www.myapp.com/backend/packingplan/all?owner=62443cb7d0f6b2006a8526e5' from origin 'https://myapp.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.
So I wonder if I can tell Axios somehow to use the URL that is defined in the browser? If the user is visiting the site via www.myapp.com it should use that as Base URL for Axios and if the user is visiting the site via myapp.com it should use that one?
How can I achieve that? Any ideas?

Related

Is there any flutter web package for google place autocomplete/search with javascript sdk?

I have tried manually using https://maps.googleapis.com/maps/api/place/autocomplete/json
?input=hyderabad&key=YOUR_API_KEY api but when I deploy app to server, CORS issue occurs.
CORS Error :
Access to XMLHttpRequest at 'https://maps.googleapis.com/maps/api/place/autocomplete/json?input=duragm+cheruvu&key=YOUR-API' from origin 'https://somedomain.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.
How to get rid of this CORS error after deployment? Or can we have any flutter web package?

how to use proxy for axios

im writing webapp and my frontend is running on
http://localhost:3000
and backend is running on
http://localhost:4000
i want use axios to do a get request on this url "http://localhost:4000/api/v1/products"
so i make a proxy in package.json file like this
"proxy": "http://127.0.0.1:4000"
and i did a get requset like this
const { data } = await axios.get("/api/v1/products")
but axios is ignore the proxy and requesting above get request from "localhost:3000"
as show here
how can i do a get request from "localhost:4000" this url insted of "localhost:3000" ?
it seems you add your proxy in the wrong file please check the proxy should add to the package.json file that belongs to your react app

Nuxt & Strapi - Logging in with OAuth using Github

I am setting up a community website with a Strapi CMS backend and a NuxtJS frontend using the composition API.
Besides the normal registration and login using email and username (which works!), I want users to be able to login using GitHub.
I am using #nuxtjs/auth module for authorization.
I've "deployed" my Strapi backend using ngrok. This is needed apparently to make OAuth work.
I've set up my GitHub application, using <ngrok-url>/connect/github/callback as the callback.
I've set the GitHub client_id and secret in my .env file.
In the strategies in my nuxt.config.js file I have this:
github: {
clientId: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET,
},
I've added a line in config/server.js of the Strapi backend:
url: '<ngrok url>'
So the backend is fired up in that location.
In my Strapi configuration, I've enabled a GitHub provider, and I need a redirect url to my frontend there. I am not sure what to put here.
I've tried: http://localhost:3000 (my Nuxt app port), but then I get a redirect uri mismatch error ("the redirect uri must match the registered callback"), when I try to access it from the frontend (using nuxt-auth's loginWith('github)').
More info on this here, but I don't get what they are saying.
Provide a redirect_uri where?
And they say to have a redirect_uri that matches what you registered. That matches what exactly?
The nuxt-auth docs are not that elaborate, saying to use $auth.loginWith('github') and that's it. I do this in my frontend, but I'm not sure if that is all I should do.
I can go manually to "<ngrok-url>/connect/github" (in ingognito) and login there in GitHub and I get redirected to the url I put in Strapi, with the access token as a parameter. So that part seems to work.
My main 2 question are:
How do I make the correct call from the frontend to the right endpoint to login through GitHub?
How do I process the result of that call?
Any help is much appreciated!
Update #1
I added a property redirectUrl on the github strategy in nuxt.config.js with the <ngrok-url>/connect/github/callback. That fixes a redirecting issue from GitHub.
I also added a redirect in Strapi to localhost:3000/connect/github and added a page in nuxt following this solution.
Now, I get back a jwt token and a user from Strapi, but $auth.loggedIn is still false in my front end. I'll try to fix this by writing my own middleware. I think this is needed because the app is server-side rendered.
The issue was that loginWith('github') connects nuxt directly to github. But we want to go to Strapi first. So in the end, I removed all the github-related info in my frontend and made a regular <a> with href to <strapi-url>/connect/github and then handled the response in a vue page like so:
data() {
return {
provider: this.$route.params.provider,
access_token: this.$route.query.access_token,
}
},
async mounted() {
const res = await this.$axios.$get(
`/auth/github/callback?access_token=${this.access_token}`,
)
const { jwt, user } = res
await this.$auth.setUserToken(jwt)
this.$auth.setUser(user)
this.$router.push(`/`)
},
To test it locally, I used ngrok to fire up the backend in a tunnel, instead of localhost.
If you want to look at more code, check out my PR here

Angular2, REST Service POST Call error : "Cross-Origin Request Blocked"

I am trying to call REST APIs from development environment(localhost:4200) using Angular 2 (version 4.0.0)
getting the below error message:
"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:8000/auth. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)."
Here I am providing a code sample for reference:
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
return this.http.post(this.loginUrl, 'POST_Parameters', {
headers: headers
}).map(res => {
console.log(res);
});
Can someone please help me to find out solution for this issue?
CORS must be enabled by backend. Depending on backend framework, usually you must send specific header that backend can recognize. But until you explicitly enable CORS support on backend, sending header is useless
on a project of mine i just went to my server (apache2 on linux 16.04 ) and i just added the "Header set Access-Control-Allow-Origin "*"" on the virtual server config file
As per Browser policy CORS is not allowed. If you are using POSTMAN then this error won't not occur.
CORS error should only remove by server side. Hence you should set header in your backend code.
If you are using express as your backend ...
app.use(function(req,res){
res.header('Access-Control-Allow-Origin', '*');});
You are in local server. You need to run api and angular app on same server.
When you upload project on same production server I hope This error will not shown.

JIRA REST API cors

I keep getting the following CORS error when trying to consume the JIRA ReST API:
Fetch API cannot load
https://jira.our-domain-name.com/jira/rest/api/2/search?jql=project=tcc%20and%20cf[10809]~8423362.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'https://application-url.our-domain-name.com' is therefore not allowed
access. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled.
However, this search URL works 100% when I paste it directly into the browser, or running it through Postman, or using CURL from command line.
My app is calling the API, using the javascript fetch API. I set the following headers when making the GET request:
headers: {
"content-type": "application/json",
"authorization": "Basic <<encrypted>>"
}
I have ensured that the requesting host has been whitelised in JIRA admin - I have tested the host using the test feature on the whitelist page.
When I change the whitelist from wildcard to Domain Name, I suddenly get this:
Fetch API cannot load
https://jira.our-domain-name.com/jira/rest/api/2/search?jql=project=tcc%20and%20cf[10809]~8423362.
Request header field authorization is not allowed by
Access-Control-Allow-Headers in preflight response.
Any ideas?
You have 2 options.
The easiest way is to proxy your request through your backend (if that's possible) since the CORS restrictions are enforced on JavaScript running within the browser.
The other way would be to reconfigure the Tomcat server that Jira is running on to support sending a CORS header. This can have other security implications if not done right.