I am new to ember .I designed an ember app and integrate the fb login in it and have to send facebook accesstoken to app backend (post request) and fetch the token generated by backend(rails).
My Post request response is:
{
"token":"71fcb8c39dc6449e2ac8e88d21e4d008cf746e16a774aa8755f6be0dbc43849265f9010111986a912fde60de4f76eb5a600ec286b26ea0a865cc7f5cab49330a",
"user":{"role":"unverified"}
}
and the component is
import Ember from 'ember';
export default Ember.Component.extend({
fb: Ember.inject.service(),
session: Ember.inject.service(),
authenticate: function(accessToken) {
console.log("accesstoken: "+accessToken);
Ember.$.ajax({
url: "http://localhost:3000/v1/sessions/fb_login",
accepts: 'application/json',
data: { token: accessToken},
crossDomain: true,
headers: {
'Client-Key': '403cb982d0c48473bee32b41b6765e15a26c595c689c620cece5fc15370c33c9c9f6d071f84bf6b88baf466f653f44b4524634bde6fbe68f065f06268f7ed7e2',
},
type: 'post',
success:function(data){
console.log('data is '+data);
}
});
},
actions: {
fb_login() {
this.get('fb').login().then((response) => {
if (response.status === 'connected') {
let fbToken = response.authResponse.accessToken;
this.authenticate(fbToken);
} else if( response.status === 'not_authorized') {
// code for not authrized
// this.transitionTo('/');
} else {
// code for facebook login
// this.transitionTo('/');
}
}).catch(() => {
// this.sendAction('check','/');
});
},
}
});
But after ajax call success is never get called to I am unable to get the the response and browser always responds with:
pretender.js:132 XHR finished loading: POST "http://localhost:3000/v1/sessions/fb_login".
Somebody please explain me how the ajax work in ember for api calls.
Related
I'm backend guy who wants to gain some Vue.js skills. In my app I've got Ruby on Rails as backend and Vue.js as front-end with a standard JWT token flow. I'm trying to send a POST request (fetchAllProductsRequest) to the backend that will trigger some background job using below code:
index.js
const fetchAllProductsRequest = (self) => {
const jwtToken = self.$store.state.idToken;
return axios
.post(`/api/v1/imports/products/fetch_all`,{
headers: {
Authorization: `Bearer ${jwtToken}`,
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(response => response.data)
};
Quite surprisingly I get an error: Request failed with status code 401. When I debugging it on the backend side I see that I send an empty token inside the header:
[1] pry(#<Api::V1::Imports::ProductsController>)> params[:headers]
=> #<ActionController::Parameters {"Authorization"=>"Bearer null", "Content-Type"=>"application/json", "Accept"=>"application/json"} permitted: false>
Here is a function that triggers fetchAllProductsRequest which is responsible for POST request:
fetch_all.vue
<script>
import {
fetchAllProductsRequest,
} from '../../api/imports'
import ModalController from '../general/modal_controller'
export default {
name: 'BackboneFetchAll',
data() {
return { }
},
components: {
MoonLoader
},
computed: {
databaseSyncInProgress() {
return this.$store.getters.getDatabaseSyncStatus;
},
},
methods: {
async syncAll() {
let confirmationText = `Do you want to sync all Backbone products?`
if (await ModalController.showConfirmation('Confirmation', confirmationText)) {
try {
ModalController.showLoader()
await fetchAllProductsRequest(this)
this.$store.commit('setSyncingProductsInProgress', value)
const successMessage = `Database synchronization has been queued`
await ModalController.showToast('', successMessage)
} catch (data) {
const errorMessage = `Error occurred during queueing products to sync - `
ModalController.showToast('', errorMessage + data?.message, 'error')
} finally {
ModalController.hideLoader()
}
}
},
}
}
</script>
What did I missed?
I am trying to get the status of a request I do from a React website I am working on, using axios to fetch make requests to a RoR API I developed. I would like to confirm that the POST request succeeded by accessing the status value from this (which is the output of a console.log(response):
Promise { <state>: "pending" }
<state>: "fulfilled"
<value>: Object { data: {…}, status: 201, statusText: "Created", … }
config: Object { url: "pathname", method: "post", data: "{\"user\":{\"email\":\"lou10#email.com\",\"username\":\"lou10\",\"password\":\"azerty\"}}", … }
data: Object { data: {…} }
headers: Object { "cache-control": "max-age=0, private, must-revalidate", "content-type": "application/json; charset=utf-8" }
request: XMLHttpRequest { readyState: 4, timeout: 0, withCredentials: false, … }
status: 201
statusText: "Created"
<prototype>: Object { … }
index.jsx:51:11
But when I try a console.log(response.status) all I get is an undefined.
Here is the code :
import axios from 'axios';
import { BASE_URL } from "./config.js";
const post = async (
endpoint,
body = null,
jwt_token = null,
header = { "Content-Type": "application/json" }) => {
let opt = header;
if (jwt_token){
opt["Authorization"] = jwt_token
}
try {
const response = await axios.post(BASE_URL + endpoint, body, { headers: opt })
return response
} catch (err) {
console.error(`An error occurred while trying to fetch ${endpoint}. ${err}`);
}
}
export default post;
const handleSignup = async ({ email, username, pwd }) => {
let body = {
user: {
email: email,
username: username,
password: pwd
}
};
return await post("/users", body);
};
useEffect(() => {
if (passwordCheck === false) {
console.log("Passwords do not match");
} else if (passwordCheck === true && userData) {
const response = await handleSignup(userData);
console.log(response.status);
// history.push({ pathname: "/", state: response.status });
}
}, [passwordCheck, userData]);
I am thinking to change the response from my API, but I really doubt it is the right approach.
Edit 1: adding some complementary code
you have to declare the function you give in parameter to useEffect as async to be able to use await inside for your async function handleSignup
useEffect(async () => {
if (passwordCheck === false) {
console.log("Passwords do not match");
} else if (passwordCheck === true && userData) {
const response = await handleSignup(userData);
console.log(response.status);
// history.push({ pathname: "/", state: response.status });
}
}, [passwordCheck, userData]);
I'm trying to add an subscriber to my Mailchimp list when the following meteor method runs.
I'm getting an error: Parameter "url" must be a string, not object.
import { Meteor } from "meteor/meteor";
import { check } from "meteor/check";
import { Logger } from "/server/api";
import request from "request";
import fetch from "isomorphic-fetch";
const methods = {
"myproject/addToMailchimp": (email) => {
check(email, String);
Logger.info(`contact person at ${email}`);
const request2 = request("https://us16.api.mailchimp.com/3.0/lists/<LISTID>/members", {
method: "POST",
headers: {
"content-type": "application/json"
},
mode: "no-cors",
json: {
email_address: email,
status: "subscribed"
},
redirect: "follow",
auth: {
user: "<USERNAME>",
pass: "<APIKEY>"
}
});
fetch(request2).then((data) => {
console.log(data);
});
}
};
Meteor.methods(methods);
I would really appreciate any help on this. I've never used fetch or request before, so I reckon I'm not using these correctly.
Thanks!
Will
When I'm logging in, it seems my data response different I'm confused cause I'm looking for access_token and refresh_token but the only available here X-CSRF-TOKEN and X-XSRF-TOKEN then there's no more other token
BTW, I'm using vue js and I want to store my access_token to localStorage. And also I'm using default laravel authentication for the login
export default{
$validates: true,
data(){
return{
login:{
username : '',
password : '',
remember : ''
},
disabled: 0,
indeterminate : false,
showLoader: false
}
},
methods:{
submit(){
this.showLoader = true;
this.$validator.validateAll().then((result) => {
if(result){
console.log(this.login.username);
/*axios.post('/prod/login', this.login)
.then(response => console.log(response));*/
axios({
method:'post',
url : '/prod/login',
data: {
email : this.login.username,
password : this.login.password,
remember : this.login.remember
},
responseType: 'JSON'
})
.then(response=>{
if(response.status == 200){
console.log(response);
}
})
.catch(error => {
if (error.response) {
console.log(error.response);
}
});
console.log('submited');
return;
}
console.log('mali e');
});
}
},
mounted(){
}
}
I am using ember-django-adapter with ember-simple-auth and have written the custom authorizer for token authentication. I am able to obtain the token from server but not able to inject it into the api requests using the adapter.
app/authorizers/application.js
import Ember from 'ember';
import Base from 'ember-simple-auth/authorizers/base';
const { service } = Ember.inject;
export default Base.extend({
session: service('session'),
init: function () {
console.log('Intialize authorizer');
},
authorize(data, block) {
const accessToken = data['access_token'];
if (this.get('session.isAuthenticated') && !Ember.isEmpty(accessToken)) {
block('Authorization', `Token ${accessToken}`);
console.log("authorizer called with token: " + accessToken);
}
}
});
app/adapters/application.js
import Ember from 'ember';
import DRFAdapter from 'ember-django-adapter/adapter/drf';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';
const { service } = Ember.inject;
export default DRFAdapter.extend(DataAdapterMixin, {
session: service('session'),
authorizer: 'authorizer:application'
});
app/authenticators/token.js
import Ember from 'ember';
import Base from 'ember-simple-auth/authenticators/base';
export default Base.extend({
serverTokenEndpoint: 'http://localhost:8000/ember-auth/',
authenticate: function(email, password) {
return new Ember.RSVP.Promise((resolve, reject) => {
Ember.$.ajax({
url: this.serverTokenEndpoint,
type: 'POST',
data: JSON.stringify({
email: email,
password: password
}),
contentType: 'application/json;charset=utf-8',
dataType: 'json'
}).then(function(response) {
console.log('Got token: ' + response.token);
Ember.run(function() {
resolve({
token: response.token
});
});
}, function(xhr) {
var response = xhr.responseText;
Ember.run(function() {
reject(response);
});
});
});
},
invalidate: function() {
console.log('invalidate...');
return Ember.RSVP.resolve();
}
});
Ember tries to transition to protected route but due to non injection of Authorization header the request fails with 403 error.
Any help is appreciated.