Unable to do a Nuxt axios post - axios

I have spent some hours trying to figure out my problem without any success.
before reading the explanation
My nuxt site generates dynamic content and works well on client side but for SEO to work and social media shares render dynamic content i need to move my app to SSR. This axios post request do work on client side rendering but does not on SSR and I don't understand the reason and I need help to understand it.
Thanks
For starters I am building a Nuxt app that consumes Drupal as a CMS using a fully decoupled approach and I have been using it for several VUE apps without problem and now I need to do them on Nuxt with a SSR approach because I need heavy SEO on the sites. With Nuxt the same request against oauth/token on drupal doesn't work and I have gone from the complex structure we had to the simple one using both Axios and Nuxt/Axios without any success and alway getting a 400 error code.
I need to run this code first on my app so I can get drupal access token and do some request for data.
Code on store
export const actions = {
async nuxtServerInit({dispatch}, vuexContext, context, app){
await dispatch("setToken");
},
async setToken({ commit, dispatch, getters }, context) {
//prep form data to send
const FormData = require('form-data');
const body = new FormData();
body.append("param1", apiConfig.getValue("param1"));
body.append("param2", apiConfig.getValue("param2"));
body.append("param3", apiConfig.getValue("param3"));
body.append("param4", apiConfig.getValue("param4"));
body.append("param5", apiConfig.getValue("5"));
await this.$axios.$post(url, body)
.then(({data}) => {
//code to process data
commit("SET_TOKEN_DATA", data);
}).catch(error => {
console.log(error)
}).finally(() => {
console.log("FINALY");
});;
}
Some updates
base url is defined on nuxt.config as
// module options for axios
axios: {
baseURL: 'mysite.com'
},
I have tied on http request the following request using both axios and nuxt/axios, I will write short request just to show what I edid
await this.$axios.$post('mysite.com/oauth/token', body)
await this.$axios.$post('/oauth/token', body)
await this.$axios.$post('oauth/token', body)
I have also tried to use
const api = $axios.crate({
baseURL: 'url'
})
api.$axios.post('oauth/token', body)
another updated
Crated a Client Side Nuxt app and the request works.

Fix it, after literally 16 hours trying. When multiform post data you need to send FormData headers on the post and again, this works without any issues using CSR on VUE and Nuxt.
await this.$axios.$post(url, body, { headers: body.getHeaders()}).yada
I don't know if it's Axios or Nuxt the one doing this but I followed a breadcrumb trail to this post https://github.com/axios/axios/issues/318

Related

Using MultiPartRequest to upload file in flutter web

So im currently trying to send images from file picker to an api that had a file input, here is the postman display and the thing was, i've tried it with numerous way that was in other post, but none of them is working for me, this is the error that i get from my web browser console and this is the code that i've tried to work with:
var postUri = Uri.parse(constanta.getMyid());
http.MultipartRequest request = new http.MultipartRequest("POST", postUri);
http.MultipartFile multipartFile = await http.MultipartFile.fromBytes(
'data', image);
request.files.add(multipartFile);
http.StreamedResponse response = await request.send();
print(response.statusCode);
i don't think the main problem was the CORS, because the api log is indicating that the request is received, but no file was attached to that request.
additional note : i've tried everything from the client side, and i cannot open/edit the backend, because it's a third party api (not owned by me).
As I can see your errors main problem here first is data was rejected from your Server as the server not allowing you to upload files and throw Cross-Origin Access which you have to solve first and then you should try.
If your postman is able to upload images on server that is because postmen itself capable of solving Cross-Origin Acess Error, so here is the solution for the node.js
If your backend is in node js you can inject the below code into your middleware.
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'XMLHttpRequest,Origin,X-Requested-With,Content-Type,Accept,Authorization');
if (req.method === 'OPTIONS') {
res.header('Access-Control-Allow-Methods', 'PUT,POST,PATCH,DELETE,GET');
return res.status(200).json({});
}
next();
});
Or you can use localhost as a backend server.

Post request to Pardot FormHandler with Axios, CORS issue

I am trying to do post request with Axios to Pardot FormHandler, but couldn't send the data. Pardot throws CORS error. I did some search and it's looks like pardot form doesn't take any data that is coming from Axios/Ajax. So to prevent this, I tried to send it as formdata which is like below...
submit(){
var bodyFormData = new FormData();
bodyFormData.append('LastName', "test");
bodyFormData.append('FirstName', "test");
bodyFormData.append('email', "example#gmail.com");
axios({
method: 'post',
url: 'https://go.pardot.com/l/pardotformurl',
data: bodyFormData,
headers: {'Content-Type': 'multipart/form-data' }
})
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
})
},
I am sending it as formdata but still an error. By the way. If I don't use axios and just send it as a <form actions="/" method="post" /> then it's goes without a problem. But, I need to use axios for this job. So is there anyway to achieve this problem..?
Pardot doesn't support submitting data to form handlers via axios, fetch or XHR. When attempting to submit data to a form handler using that, you will likely see errors like:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '{page from which form handler should be getting submitted on client's website}' is therefore not allowed access.
This is what's known as CORS (Cross-Origin Resource Sharing). Pardot doesn't currently support CORS or JSONP for form handlers. It is possible to simulate a JSONP response by setting the Success and Error URLs for the form handler to be JavaScript URLs that execute Success and Error callbacks, respectively.

Facebook Webhook Test Button not working as expected

I have successfully added my callback url in my webhooks setup. At that time, the callback url was called successfully with proper logs and everything in the server. But when I click on the TEST button for the respective name (leadgen in this case), nothing AT ALL is being received by the server when in fact it should at least log the very first line. Note that I am using post and get.
Additional note: for NetSuite experienced developers, I am using a suitelet as the callback url for the webhook.
Thanks.
Suitelets that are available externally without login will only work if the User-Agent header in the request mimics a browser. See for example SuiteAnswers # 38695.
I ran into a similar issue, and the workaround was to proxy the request using a Google Cloud Function that simply rewrote the User Agent:
const request = require('request');
exports.webhook = (req, res) => {
request.post(
{
url: process.env.NETSUITE_SUITELET_URL,
body: req.body,
json: true,
headers: {
'User-Agent': 'Mozilla/5',
Authorization: req.headers['authorization'],
},
},
function(error, response, body) {
res.send(body);
}
);
};

Axios post request is not working in Ionic 2

I'm trying to get oauth token from my laravel app to my ionic 2 app.But it got error. How to solve it ?
It work fine in browser but when i emulate it it doesn't work.
Login.ts (ionic)
getLogin(event) {
oauth_credentials.username = 'rafsanhashemi#gmail.com';
oauth_credentials.password = 'secret';
axios.post(route.oauth_token, JSON.stringify(oauth_credentials),
{headers: {'Content-Type': 'application/json'}})
.then( res => {
console.log(res)
this.selectedItem = res.data;
})
.catch( err => {
console.log(err.data)
this.selectedItem = 'err';
})
}
Error what i got . How to fixed it ?
I advice you to use Angular HttpClient https://angular.io/guide/http
Most front-end applications communicate with backend services over the HTTP protocol. Modern browsers support two different APIs for making HTTP requests: the XMLHttpRequest interface and the fetch() API.
With HttpClient, #angular/common/http provides a simplified API for HTTP functionality for use with Angular applications, building on top of the XMLHttpRequest interface exposed by browsers. Additional benefits of HttpClient include testability support, strong typing of request and response objects, request and response interceptor support, and better error handling via apis based on Observables.

Connection between nativescript and MongoDB (mongoose)

I am new in mobile development world and right now trying to understand few basic things.
I did a simple login nativescript app and from backend side did a login logic with mongoose (MongoDb) and express. But now I don't know how to proceed... How do I connect between backend and app?
Thank you in advance,
Emil
You need to expose an API from your backend, I'll assume you have done this (or can find this out - it's very well documented).
So from the client {N} you will need to access the API, calling whichever end-points you need. If you were using a JWT type approach, you should use the http module in nativescript, which might look something like this:
var http = require("http");
var result;
http.request({
url: "https://myBackend.org/api/post",
method: "POST",
headers: { "Content-Type": "application/json" },
content: JSON.stringify({ username: "ValueOne", password: "ValueTwo" })
}).then(function (response) {
result = response.content.toJSON();
console.log(result); //result.message would have the clients auth token
}, function (e) {
// console.log("Error occurred " + e);
});
You could then store the token (in persistent storage with the application-settings module) and add it to the header of any request to a different API endpoint to interact with your backend as an authenticated user.
Alternatively, you can use one of the cloud backend SDKs, e.g. Azure Mobile Services or Firebase which make your life much easier.