Post request with useAxios - vue.js

I am trying to use the composition api on my Vue app, and I need to do a post request to my backend api. I am trying to make use of the "useAxios" utility from vueuse, but I can't figure out how to pass data into a post request. It isn't shown properly in the docs...
I want to convert the following axios request into one that uses "useAxios".
await axios.put(`/blog/posts/${route.params.postID}/`, post.value)
.then(() => notification = "Post Created!")
.catch(() => {
error = "Failed to create post"
});
I tried setting the value of the data field, but that didn't work...
const {data, execute, isFinished} = useAxios(axios)
data.value = post
await execute(`/admin/blog/posts/${route.params.postID}/`, {method: "PUT"})
I also tried passing the post object into the execute method as a parameter, but my ide complained.
Thanks in advance!

Set up your pending request ahead of time:
const { data, execute, isFinished } =
useAxios(`/admin/blog/posts/${route.params.postID}/`,
{ method: "PUT" },
{ immediate:false });
Then in the future you can call it by passing the data as follows:
const requestBody = { /* your data */ };
await execute({ data: requestBody });

Related

How do I pull data out of response or cache for apollo client 3

I am trying to pull a jwt out of a loginUser mutation and store it in a variable then use the apollo-link to setContext of the header via "Authorization: Bearer ${token} for authentification as all my other mutations and queries require the token. I have been slamming the docs for days on Apollo Client(React) -v 3.3.20. I have been through all the docs and they show all these examples of client.readQuery & writeQuery which frankly seem to just refetch data? I don't understand how you actually pull the data out of the response and store it in a variable.
The response is being stored in the cache and I have no idea how to take that data and store it in a token variable as I stated above. Which remote queries I can just access the returned data via the data object from the useQuery hook, however on the useMutation hook data returns undefined. The only thing I could find on this on stack overflow was the my data type may be custom or non-traditional type but not sure if that is the problem.
[Cache in apollo dev tools][1]
[Mutation in apollo dev tools][2]
[Response in network tab][3]
Here is my ApolloClient config:
const httpLink = createHttpLink({ uri: 'http://localhost:4000/',
// credentials: 'same-origin'
});
const authMiddleware = new ApolloLink((operation, forward) => {
const token = localStorage.getItem('token');
// add the authorization to the headers
operation.setContext(({ headers = {} }) => ({
headers: {
...headers,
authorization: `Bearer ${token}` || null,
}
}));
return forward(operation);
})
const client = new ApolloClient({
cache: new InMemoryCache(),
link: concat(authMiddleware, httpLink),
});
The header works obviously I just can't grab the token to pass so the header just sends Authorization: Bearer.
For the login I have this:
const LOGIN_USER = gql`
mutation($data:LoginUserInput!) {
loginUser(
data: $data
) {
user {
id
name
}
token
}
}
`;
const [loginUser, { data, loading, error }] = useMutation(LOGIN_USER);
if (loading) return 'Submitting...';
if (error) return `Submission error! ${error.message}`;
Originally I was just calling
onClick={loginUser( { variables })}
For the login but onComplete never works and everywhere I look I see lots of posts about it with no solutions. So I tried slamming everything into a function that I then called with loginUser inside it:
const submit = async () => {
loginUser({ variables})
// const { user } = await client.readQuery({
// query: ACCESS_TOKEN,
// })
// console.log(`User : ${JSON.stringify(user)}`)
const token = 'token';
const userId = 'userId';
// console.log(user);
// localStorage.setItem(token, 'helpme');
// console.log({data});
}
At this point I was just spending hours upon hours just trying mindless stuff to potentially get some clue on where to go.
But seriously, what does that { data } in useMutation even do if it's undefined. Works perfectly fine for me to call data.foo from useQuery but useMutation it is undefined.
Any help is greatly appreciated.
[1]: https://i.stack.imgur.com/bGcYj.png
[2]: https://i.stack.imgur.com/DlzJ1.png
[3]: https://i.stack.imgur.com/D0hb3.png

Managing Gcal Response + express and header issue

I'm new to node and banging my head against a wall on what should be a simple node+express+googlecal+pug issue
node/express route accepts requests and calls controller
controller ensures validation of auth and then...
executes a successful gcal function...console.log has the data i need
trying to directly (in controller function) returns "Cannot set headers after they are sent to the client"....why is a call to Gcal API forcing a response back to client?
Trying to make it more micro via individual calls to each function results in same result
What am I missing here?
getcalendars: async function(oAuth2Client, res) {
const calendar = google.calendar({ version: "v3", auth: oAuth2Client });
cal = await calendar.calendarList.list(
{},
(err, result) => {
//console.log("HEADERS SENT1?: "+res.headersSent);
if (err) {
console.log('The API returned an error: ' + err);
return;
}
console.log(JSON.stringify(result));
message2 = JSON.stringify(result)
res.render('schedules', {message2: message2})
return
});
},
EDIT: Calling function
router.route('/dashboard/schedules')
.get(async function(req, res) {
if (req.session.loggedin) {
//x = gcalController.getcalendars(req, res);
token = await gcalController.gettoken(req, res);
isAuth = await gcalController.calauth(token);
listcalendars = await gcalController.getcalendars(isAuth,res);
} else {
res.redirect("/?error=failedAuthentication")
//res.send('Please login to view this page!');
}
});
Can't set headers already sent happens when you're sending a response more than once. Usually you can terminate the function by returning your res.send() call.
It looks like the express middleware that created the res object is sending a response by the time your res.render() gets pulled out of the microtask queue.
Can you show the full code? It seems that this is probably originating in the scope where getcalendars is called.

Testcafe multiple requests to endpoint synchronously not working

Currently I am setting up testcafe and have hit a hurdle when making a request to the same endpoint.
This is an authentication request. The steps are currently:
Initial request is sent to server which responds with a body. This is awaited
Once step is retrieved from step 1 this is mutated and sent back to the server.
We then the same endpoint and pass in the body generated in step 2
But I am having issues in the testcafe tests as it always using the first request and returns that twice.
I have referred to this issue on testcafe https://github.com/DevExpress/testcafe/issues/2477 however this did not work.
const mock = (mockResponse, status) => {
return RequestMock()
.onRequestTo(/\/apitest\/authenticate\)
.respond(mockResponse, status, {
"Access-Control-Allow-Origin": "http://localhost:3000",
"Access-Control-Allow-Credentials": "true"
});
};
const mock1 = mock(RESPONSE1, 200);
const mock2 = mock(RESPONSE2, 200);
test.requestHooks(mock1)(
"Should redirect to error if user has been suspended after submitting",
async t => {
const usernameInput = Selector("#username");
const mobileDigitOne = Selector("#mobile-digit-0");
const mobileDigitTwo = Selector("#mobile-digit-1");
const mobileDigitThree = Selector("#mobile-digit-2");
const submitButton = Selector("#submit-button");
await t
.typeText(usernameInput, "username123456")
.click(digits)
.typeText(digits, "123456")
.click(submitButton);
await t.removeRequestHooks(mock1);
await t.addRequestHooks(mock2);
Any ideas on how to request same endpoint multiple times?
You can distinguish different requests to the same endpoint using the request body. You can pass different kinds of filter to the mock's onRequestTo method, including a predicate function. Refer to the Filter with a Predicate article for more details.
Thus, you can use a single mock for both requests, like this:
function isTheSecondRequest(requestBody) {
// This should return `true` for the mutated request body
// and `false` for the original one.
//
// For example:
return requestBody.indexOf('{ foo: bar }') !== -1;
}
const mock = RequstMock()
.onRequestTo(request => {
request.url === '/apitest/authenticate' &&
!isTheSecondRequest(request.body)
})
.respond(RESPONSE1, 200, HEADERS)
.onRequestTo(request => {
request.url === '/apitest/authenticate' &&
isTheSecondRequest(request.body)
})
.respond(RESPONSE2, 200, HEADERS);

React Native fetch POST variables not received on server

I have tried different ways with fetch or axios to POST to my server but it seems that the post body turns empty . My initial code is this.
So the connection to the server is good. I have configured server to respond with $_POST variables received but the $_POST return empty. This happens when I use JSON.stringify on body. I have also tried with FormData and it works fine but only on iOS. On my Android device and emulator I get Possible Unhandled Promise: Network request failed error (both https and http).
And I want to make it work on both iOS and Android. So till now I have manage to send post with formData only on iOS.
Any Solutions that works on Android and iOS?
import FormData from "FormData";
export const login = (emailUsername, password) => {
var formData = new FormData();
formData.append("emailUsername", emailUsername);
formData.append("password", password);
return async dispatch => {
const response = await fetch(
"https://myserver.net/api/app/auth.php",
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
emailUsername:emailUsername,
password:password
})
}
);
if (!response.ok) {
throw new Error("Something went wrong!");
}
const resData = await response.json();
console.log(resData);
};
};
Thanks to #bug I have find a solution. I was expecting to receive POST content to my $_POST or $_REQUEST variables on my server, but instead I had to get them this way.
$post_data = json_decode(file_get_contents('php://input'));

vue-resource not passing token in request headers

I'm new to Vuejs 2, currently using vue-resource to retrieve data from the server. However, I would need a token passed in the request header at the same time in order to retrieve the data from the server.
So the problem is, I am unable to retrieve data because the token is not passed into the request header, using vue-resource.
Here is the method that uses the vue-resource's interceptor (to pass in the token) to intercept the GET request:
test () {
this.$http.interceptors.push((request) => {
var accessToken = window.localStorage.getItem('access_token')
request.headers.set('x-access-token', accessToken)
return request
})
this.$http.get(staffUrl)
.then(response => {
console.log(response)
}, (response) => {
console.log(response)
})
}
Documentation for vue-resource, HTTP: https://github.com/pagekit/vue-resource/blob/develop/docs/http.md
When I try to GET the data, i end up with an error 403 (forbidden) and after checking the request headers in the dev tools, I also could not find the token in the request headers.
Please tell me where I went wrong because I'm really new to this so i appreciate any help! Thank you!
Setting interceptors inside the component using $http doesn't work, or at least it doesn't in my testing. If you examine/log this.$http.interceptors right after your push in the test method, you'll note that the interceptor was not added.
If you add the interceptor before you instantiate your Vue, however, the interceptor is added properly and the header will be added to the request.
Vue.http.interceptors.push((request, next) => {
var accessToken = "xyxyxyx"
request.headers.set('x-access-token', accessToken)
next()
})
new Vue({...})
Here is the test code I was using.
Also note, if you are using a version prior to 1.4, you should always call the next method that is passed to the interceptor. This does not appear to be necessary post version 1.4.
please go through this code
import vueResource from "vue-resource";
import { LocalStorage } from 'quasar'
export default ({
app,
router,
Vue
}) => {
Vue.use(vueResource);
const apiHost = "http://192.168.4.205:8091/";
Vue.http.options.root = apiHost;
Vue.http.headers.common["content-type"] = "application/json";
Vue.http.headers.common["Authorization"] = "Bearer " + LocalStorage.get.item("a_t");
Vue.http.interceptors.push(function(request, next) {
console.log("interceptors", request);
next(function(response) {
});
});
}