React form submit is creating phantom parameters - ruby-on-rails

I have a basic registration form in a React front end app, that sends the input parameters to a rails-api backend.
The function to do so looks like this:
handleSubmit(event) {
event.preventDefault();
Axios.post('http://localhost:3001/auth/', {
'password': 'password',
'password_confirmation': 'password',
'email': 'asdf#asdf',
'first_name': 'asdfasdf',
'last_name': 'wefawa',
'handle': 'awfewwe'
})
.then(function (response) {
alert(response);
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
When I send this though, the params on the rails-api backend somehow include a second copy of each parameter, nested under the key "registrations" The full text, copied from console logs:
"Started POST "/auth/" for ::1 at 2018-01-12 00:36:07 -0500
Processing by Overrides::RegistrationsController#create as HTML
Parameters: {"password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "email"=>"asdf#asdf", "first_name"=>"asdfasdf", "last_name"=>"wefawa", "handle"=>"awfewwe", "registration"=>{"password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "email"=>"asdf#asdf", "first_name"=>"asdfasdf", "last_name"=>"wefawa", "handle"=>"awfewwe"}}"
Any idea where that registration tag is coming from?
I realize this is a rather specific question, but any help is much appreciated.
Thanks!

My Own Answer
I had to rearrange the syntax somewhat, but the following worked:
handleSubmit(event) {
event.preventDefault();
Axios.request({
url: 'http://localhost:3001/auth/',
method: 'post',
params: {
'password': 'password',
'password_confirmation': 'password',
'email': 'possible2#example.com',
'first_name': 'asdfasdf',
'last_name': 'wefawa',
'handle': '#notusedyet2'
},
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}

Related

Rails API, devise user registration, CORs signup with Vue Js

I have a curious CORS error in a Rails API setup with post request from Vue signup,
Despite setting the values at localhost:8080 for the Vue app and localhost:3000 for the response, it still wont allow access.
Rails CORs settings are below.
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins 'localhost:8080'
resource 'localhost:3000',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
The request method using Nuxt axios plugin is below'
// Check submit
signin () {
this.$plain.post( '/api/v1/sign_up/', { email: this.email, password: this.password, password_confirmation: this.password_confirmation} )
.then(response => this.signinSuccessful(response))
.catch(error => this.signinFail)
console.log({ email: this.email, password: this.password, password_confirmation: this.password_confirmation });
alert('Processing!');
},
And the axios plugin code itself is also below.
/* eslint-disable */
import axios from 'axios'
export default function ({ $axios, store }, inject) {
const API_URL = "http://localhost:3000"
const secured = axios.create({
baseURL: API_URL,
withCredentials: true,
headers: {
"Content-Type": "application/json",
},
})
const plain = axios.create({
baseURL: API_URL,
withCredentials: true,
headers: {
"Content-Type": "application/json"
},
})
secured.interceptors.request.use((config) => {
const method = config.method.toUpperCase();
if (method !== "OPTIONS" && method !== "GET") {
config.headers = {
...config.headers,
"X-CSRF-TOKEN": localStorage.csrf,
};
}
return config;
});
secured.interceptors.request.use(null, (error) => {
if (error.response && error.response.config && error.response.status === 401) {
return plain
.post("/refresh", {}, { headers: { "X-CSRF-TOKEN": localStorage.csrf } })
.then((response) => {
localStorage.csrf = response.data.csrf;
localStorage.signedIn = true;
let retryConfig = error.response.config;
retryConfig.headers["X-CSRF"] = localStorage.csrf;
return plain.request(retryConfig);
})
.catch((error) => {
delete localStorage.csrf;
delete localStorage.signedIn;
location.replace("/");
return Promise.reject(error);
});
} else {
return Promise.reject(error);
}
})
inject('plain', plain)
inject('secured', secured)
}
It is getting rejected due to CORs policy for authenticated requests as in screenshot, and I tried changing "with-credentials" to false but got error bad request, any tips on this welcome?

NativeScript-Angular - POST formdata to Wordpress ContactForm7 API

Hello everyone and thanks in advance ...
I'm trying to use the Contact Form7 APIs to fill in and submit a form from an Angular NativeScript App.
I have tried different solutions but I always get the same error response.
{"into":"#","status":"validation_failed","message":"Oops, there seems to be some error in the fields. Check and try again, please.","invalidFields":[{"into":"span.wpcf7-form-control-wrap.nome","message":"Attention, this field is required!","idref":null},{"into":"span.wpcf7-form-control-wrap.mail","message":"Attention, this field is required!","idref":null}]}
In the example I have entered static values ​​in the body for convenience
Help me ;(
attempt 1
onTappedInvia(): void {
fetch("http://www.example.com/wp-json/contact-form-7/v1/contact-forms/{id}/feedback", {
method: "POST",
headers: { "Content-Type": "multipart/form-data" },
body: JSON.stringify({
nome: "Test API",
mail: "test#test.test"
})
}).then((r) => r.json())
.then((response) => {
const result = response.json;
console.log(response);
}).catch((e) => {
console.log(e);
});
}
attempt 2
deliverForm() {
var formData: any = new FormData();
formData.append('nome', "Test API");
formData.append('email', "test#test.test");
formData.append('your-message', "Test API");
this.submitted=true;
console.log(formData);
this.formService.create(formData)
.subscribe(
data => {
console.log('Invoice successfully uploaded');
console.log('Error'+ JSON.stringify(data));
},
error => {
console.log('Error'+ JSON.stringify(error));
});
console.log('USCITO');
}
and formService
const HttpUploadOptions = {
headers: new HttpHeaders({ "Content-Type": "multipart/form-data;" })
}
#Injectable({
providedIn: 'root'
})
export class FormService {
constructor(
private HttpClient: HttpClient
) { }
create(formData){
return this.HttpClient.post('http://www.example.com/wp-json/contact-form-7/v1/contact-forms/{id}/feedback', formData, HttpUploadOptions)
}
}
The problem was with the Content-Type. i tried with application/x-www-form-urlencoded and it works!
fetch("http:www.aficfestival.it/wp-json/contact-form-7/v1/contact-forms/5173/feedback?", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: form
}).then((r) => r.json())
.then((response) => {
const result = response.json;
console.log(response);
}).catch((e) => {
console.log(e);
});
}

fetch API with POST method giving me 500 (Internal Server Error)

I'm using a fetch with POST method to get data from an API in my index.html page but am getting 500 status code, can somebody please guide me on what could be wrong in my code
<body>
<h1>Flights Finder</h1>
<script type="text/javascript">
fetch("https://skyscanner-skyscanner-flight-search-v1.p.rapidapi.com/apiservices/pricing/v1.0", {
'method': 'POST',
'headers': {
'x-rapidapi-host': 'skyscanner-skyscanner-flight-search-v1.p.rapidapi.com',
'x-rapidapi-key': 'API_KEY',
'content-type': 'application/x-www-form-urlencoded'
},
'body': {
'inboundDate': '2019-11-24',
'cabinClass': 'business',
'children': '0',
'infants': '0',
'country': 'US',
'currency': 'USD',
'locale': 'en-US',
'originPlace': 'SFO-sky',
'destinationPlace': 'LHR-sky',
'outboundDate': '2019-11-16',
'adults': '1'
}
})
.then(response => {
console.log(response);
})
.catch(err => {
console.log(err);
});
</script>
</body>
Error code 500 is an internal server error. You should check if no error is being thrown on the server.

How to add a BearerToken to React API Requests?

newbie to React looking for some help... I'm using React to make API requests like so:
class CatsApi {
static createCat(cat) {
const request = new Request('http://localhost:4300/api/v1/cats', {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: JSON.stringify(cat)
});
return fetch(request).then(response => {
return response.json();
}).catch(error => {
return error;
});
}
Meanwhile, I have authentication to my API via react-devise:
https://github.com/timscott/react-devise
Which has a method getBearerToken like so: https://github.com/timscott/react-devise/blob/master/src/actions/authTokenStore.js
How do I use getBearerToken to pass the API the token so API requests are authenticated with the token?
Thank you!
You can use the Authorization header like:
{ 'Authorization': `Bearer ${authToken}` }
Using fetch you could try with something like:
fetch('http://localhost:4300/api/v1/cats', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`
'Accept' : 'application/json',
'Content-Type' : 'application/json',
},
body: JSON.stringify({
cat : cat_value,
})
})
.then((response) => response.json())
.then((responseData) => { console.log(responseData) })
.catch((error) => { console.log(error) })
.done()
Also, it'd be great to see what's the Rails output in the console when you make a request, or the browser console.

React Native fetch "unsupported BodyInit type"

I'm trying to send a POST request to the OneSignal REST API using fetch:
var obj = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
'app_id': '(API KEY)',
'contents': {"en": "English Message"},
'app_ids': ["APP IDS"],
'data': {'foo': 'bar'}
})
}
fetch('https://onesignal.com/api/v1/notifications', obj)
I know you're not really supposed to put your API key in client code, but this is just a test to see if it would work. Besides, the error I'm getting isn't a bad response from the server, it's:
Possible Unhandled Promise Rejection (id: 0):
unsupported BodyInit type
I've tried putting a catch method on the fetch, but it doesn't get called.
At a bit of a loss, not really sure how to proceed.
Thanks in advance!
Even I tried the same POST request for One-Signal REST API for creating notifications,the below worked for me fine.
const bodyObj = {
app_id: "**********",
included_segments: ["All"],
data: {"foo": "bar"},
contents: {"en": "Hi good morning"}
}
fetch('https://onesignal.com/api/v1/notifications',{
method:'POST',
headers:{
'Authorization':'Basic **********',
'Content-Type':'application/json'
},
body:JSON.stringify(bodyObj)
})
.then((response) => response.json())
.then((responseJson) => {
console.log("success api call");
})
.catch((error) => {
console.error(error);
});
Have you tried to change your json to the one below?
JSON.stringify({
app_id: '(API KEY)',
contents: {en: "English Message"},
app_ids: ["APP IDS"],
data: {foo: 'bar'}
})
Or even tried a simpler json?

Resources