Nuxtjs - Error 404 with post request in production while working in local - axios

I'm actually trying to use nuxt-mail in a personnal project,
During my development phase, I receive all my testing mails. And from there I did the following adjustments to do the exact same request from my builded site :
//nuxt.config.js
env: {
baseUrl:
process.env.NODE_ENV === 'dev'
? 'http://localhost:3000'
: 'https://my-domain.netlify.app'
},
My code when using the 'send' function :
this.$axios.$post(process.env.baseUrl + "/mail/send", {
config: 'contact',
from: document.getElementById('input-2').value,
subject: document.getElementById('subject').value,
text: "This is a text message",
})
It continues to work well with localhost/3000/mail/send but I have a 404 error once I build my site and using https:/ /my-domain.netlify.app/mail/send :
POST https://my-domain.netlify.app/mail/send [HTTP/2 404 Not Found 186ms]
Uncaught (in promise) Error: Request failed with status code 404
I'm actually struggling to solve this problem, am I missing something ?

Alright, so if your target is static, you can only do yarn generate.
If you do have the default, aka target: server, you can only yarn build.
Then, as talked about it a bit here: Sending mail in Nuxt.js with nuxt-mail
You cannot use a Node.js package in a static environment, so neither yarn generate nor Netlify will help you here. You need to yarn build and host it on something like Heroku.
One last step that you can do, is to try it locally with the following:
target: server
yarn build
yarn start
make your POST call with Postman or alike
If it does not work here, it is a code issue and you can look into the hosting one.
If it does work locally, you can proceed to the hosting issue that you'll face.

Well you just misunderstood the env field in the nuxt.config.js file.
That env field is passed to the $config Object of the Nuxt App and not passed to process.env.
What you want is to set the BaseUrl for the Axios Module
// nuxt.config.js
axios: {
baseURL: process.env.NODE_ENV === 'dev'
? 'http://localhost:3000'
: 'https://my-domain.netlify.app'
},
// or provide a runtime config
// server and clientside
publicRuntimeConfig: {
axios: {
browserBaseURL: process.env.BROWSER_BASE_URL
}
},
// serverside only
privateRuntimeConfig: {
axios: {
baseURL: process.env.BASE_URL
}
},
Edit:
Also when calling axios just do it like that if you implement the above changes
this.$axios.$post("/mail/send", {
// ... the rest of your code

Related

AWS CDK: Api Key ignored when testing api gateway locally?

I'm currently developping an API with aws-cdk and I'm testing it locally with aws-sam-cli and docker. I wanted to add the requirement of an API Key to call the API.
Here is the code inside my stack:
const api = new apigw.RestApi(this, "MyAPI", {
restApiName: "My API",
description: "BLABLABLA API",
});
const myLambdaIntegration = new apigw.LambdaIntegration(myLambda, {
proxy: false,
});
// Endpoints of the API
api.root.addResource("test").addMethod("GET", myLambdaIntegration, {
apiKeyRequired: true,
});
Then I build this stack and synth it (npm run build ; cdk synth --no-staging myStack > template.yaml
And try to test it locally
sam local start-api
When I request my api without any API KEY, the API returns me the result of my lambda. šŸ˜­
I expected it to return me an error like {"message":"Missing Authentication Token"}
Does anyone have an idea of what is going on?
I suspect it's because authorizations are ignored locally but didn't find anything about that...
Thanks in advance! šŸ˜
Edit: After deploying this stack, the API correctly asks me for a token.

Http request working on ionic serve but doesn't work on "ionic cordova run android --device"

I am using Ionic native http to make server requests. The server is hosted on aws and the apis are up and running (verified by postman).
When i do ionic serve the requests go through and work but when i try to run it on device it doesnt work. On inspection i get "net::ERR_CLEARTEXT_NOT_PERMITTED" and post is sent as OPTIONS
ERROR HttpErrorResponseĀ {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://18.220.143.133/api/login", ok: false,Ā ā€¦}
already tried adding to config.xml
login(user: User): Observable<AuthResponse> {
return this.httpClient.post('http://18.220.143.133/api/login', user, {
headers: new HttpHeaders().set('Content-Type', 'application/json'),
}).pipe(
tap(async (res: AuthResponse) => {
if (res.success == true) {
await this.storage.set('user',res.user);
await this.storage.set('ACCESS_TOKEN', res.token);
this.authSubject.next(true);
}
})
);
}
I expect http requests to go through from mobile devices as well.
The same happened to me, until in the config.xml file I added:
<preference name = "android-targetSdkVersion" value = "27" />
It has to do with your CORS for the API call. This may help. Also, since you're using Angular HTTP requests, check here HTTP request from angular will send with method OPTIONS instead of POST.

Ionic proxy config for different environments

I am new to ionic and I try to setup a proxy configuration for different environments. I have several environment-specific config files in place which get loaded using webpack and an environment variable which is set before ionic is served (see: https://github.com/gshigeto/ionic-environment-variables).
Everything works as expected but I donā€™t know how to solve following issue:
My proxy configuration (ionic.config.json) looks like this:
"proxies": [
{
"path": "/api",
"proxyUrl": "https://dv.mydomain.com/api",
"rejectUnauthorized": false
}
]
and one of my http calls looks like this:
return this.http.get<User[]>(ENV.apiUrl + '/api/users')
I have to remove ENV.apiUrl because otherwise the pattern specified in the proxy config doesnā€™t get matched, but if I do so, I cannot distinguish between different environments anymore. I have tried to add the domain to the path of the proxy configuration, which did not work.
Is there a way to solve this issue?
I asked the same question in the ionic forum but no one answered so far.
The way I "solved" it so far is not to use Ionic proxies anymore. I've installed this plugin for chrome, which basically disables chrome's CORS protection by adding Access-Control-Allow-Origin: * to the response headers.
Can't the apiUrl just be a URL path component? Ex:
// environment.pro.ts
export const environment: any = {
apiUrl: '/pro'
};
// environment.dev.ts
export const environment: any = {
apiUrl: '/dev'
};
Then, something like:
// ionic.config.json
"proxies": [
{
"path": "/pro/api",
"proxyUrl": "https://example.com/api",
"rejectUnauthorized": false
},
{
"path": "/dev/api",
"proxyUrl": "https://dev.example.com/api",
"rejectUnauthorized": false
}
]
CORS issue will only be specific to the local development as Ionic uses browser for local developement.
In mobile all the javascript will be copied as file://
Thus origin will not be exist.
So to handle this you can install the chrome extention
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en
This should solve the problem.

production build of ember app works, but when using ember serve, cookies not sent to api

I have a rest API running on localhost:8001/my_app/api/, and I have apache setup to reverse proxy it from localhost/my_app/api. That's working fine.
In order to have permissions to do anything with the api, it requires my session cookie, my csrftoken cookie and a X-CSRFToken HTTP header. I've configured adapters/application.js as follows:
adapters/application.js
import Ember from 'ember';
import DRFAdapter from './drf';
export default DRFAdapter.extend({
headers: Ember.computed(function() {
return {
'X-CSRFToken': Ember.get(document.cookie.match(/csrftoken\=([^;]*)/), '1'),
};
}).volatile(),
ajax: function(url, method, hash) {
hash = hash || {}; // hash may be undefined
hash.crossDomain = true;
hash.xhrFields = {withCredentials: true};
return this._super(url, method, hash);
}
});
If I do a ember build -prod and copy the contents of the dist dir to /var/www/myApp/, apache serves my app, and it works just fine.
It's when I try to use ember-cli's builtin development server where I run into problems. I'm getting 403 errors from my api. It turns out that while the X-CSRFToken header is being sent neither of my cookies are. If I look in my chrome developer tools, it shows that I have both cookies - they simply aren't in the request headers. They're both from localhost, so I'm a bit confused.
Also, I currently I have CORS on my rest backend setup. Here are the headers I'm currently receiving:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:4200
I thought that since allow-credentials == true and allow-origin != * that cookies were supposed to be allowed. sigh.
Here's my API_HOST and contentSecurityPolicy:
config/environment.js
if (environment === 'development') {
ENV.APP.LOG_TRANSITIONS = true;
ENV.APP.API_HOST = "http://localhost"
ENV.contentSecurityPolicy = {
'default-src': "'none'",
'script-src': "'self' 'unsafe-eval' localhost",
'font-src': "'self'",
'connect-src': "'self' localhost",
'img-src': "'self'",
'style-src': "'self'",
'media-src': "'self'"
};
}
As you can see above, the api requests are being sent through my reverse proxy. I've played around with ember serve --proxy trying both http://localhost:80/ and http://localhost:8001/ but neither have helped. I've also tried setting my development ENV.API_HOST = 'http://localhost:8001/'; with and without the various proxy values.
This edit, build, deploy, refresh my browser, test, & repeat process is REALLY slow and getting old REALLY fast.
Could someone please explain to me how to get the ember-cli development server to properly access my rest api?

Loading store data with rest proxy from server in Sencha Touch 2

I have searched around on the forums and read some other posts. However, I'm not sure how exactly to go about this. I have a store with a proxy that I'm trying to load with data from a server. I have tried both jsonp and rest for the type of proxy without luck. In both cases I get a 403 forbidden error. followed by an XMLHTTPRequest cannot load error.
Here's the error that I see in the Chrome console:
Here's my code:
Ext.define('EventsTest.store.Venues', {
extend: 'Ext.data.Store',
requires: [
'Ext.data.proxy.Rest',
],
config: {
storeId: 'venuesStore',
model: 'EventsTest.model.Venue',
proxy: {
type: 'rest',
url: 'http://leo.web/pages/api/',
headers: {
'x-api-key': 'senchaleotestkey'
},
limitParam: false,
pageParam: false,
enablePagingParams: false
/*
extraParams: {
latitude: 45.250157,
longitude: -75.800257,
radius: 5000
}
*/
}
}
});
Security policy in browser and desktop is different so even if it fails in browser it can work in phone. But now the question is how to manage while you are developing the app, for that have a look at this similar question :
How to use json proxy to access remote services during development
Regarding that OPTION request which is getting 403 response, try setting withCredentials : false and useDefaultHeader : false. Details here
http://docs.sencha.com/touch/2-1/#!/api/Ext.data.Operation-cfg-withCredentials
http://docs.sencha.com/touch/2-1/#!/api/Ext.data.Connection-cfg-useDefaultHeader
I would suggest you to read more about CORS if you want to use remote services, you may choose to enable CORS on your server.
You're running your app on a local domain "sencha.test", but you're trying to access data on "leo.web" - the error is that you're trying to load data across domains, which isn't allowed via AJAX.
You say that JSONP doesn't work... why not? Does your server return valid JSONP?