Axios seemingly manipulates passed data - javascript

My current NuxtJS Application contains the following code:
// Create a new Canvas-Object on a Whiteboard
async createCanvasObject({ state }, canvasObject) {
if (!state.id) {
console.error(' Canvas ID is not defined!');
return;
}
console.log(canvasObject);
console.log(canvasObject.mtiID);
await this.$axios
.$post(`/whiteboard/${state.id}/canvas/object`, {
object: canvasObject,
})
.then((res) => console.log(res));
},
What should this code do?
It should send a passed object canvasObject via POST-Request to my backend, without modifying it.
The canvasObject itself is a JSON-Object, which describes an Object on a Canvas.
The logging directly before the Axios-Call yields something like this:
As you can see, there is a lot of stuff defined, and espacially the attribute mtiID.
Now the Problem:
If we look at the request, we can see, that a lot of stuff got stripped away from my JSON, including the mtiID. I have no idea why. The only 'Middleware', that is currently applied to Axios just logs every request to the console, without modifying it.

Related

Pre-request script doesn't change the collection variable using Postman

Pre-Request Script:
let user_id = pm.collectionVariables.get("user_id");
pm.sendRequest(`http://security.postman-breakable.com/account/${user_id}/summary`, function (err, response) {
if(response.status == "FORBIDDEN"){
pm.collectionVariables.set("status_code", 403);
}else if(response.status == "OK"){
pm.collectionVariables.set("status_code",200);
}
});
Test:
let status_code = parseInt(pm.collectionVariables.get("status_code"));
pm.test(`Status code is ${status_code}`, function () {
pm.response.to.have.status(status_code);
});
The response code is 200 but it reads the previous response code which was 403.
Although I try to change my collection variable called "status_code" by writing pre-request script when the response code changes, it doesn't change.
I can replicate this 100% of the time. Searching for a solution brought me here.
I truly think it's a bug: it seems that Pre-request Scripts (in 10.8.7) get either a shallow copy of whatever state Collection Variables were in at time of Send, or the binding between pm.collectionVariables and Collection Variables has broken. I can't imagine that this behavior is intentional.
For now, I would suggest that you refactor this into a Request and have code in a Test do the pm.collectionVariables.set()
The following doesn't apply to your specific use case, but perhaps it will be relevant to whomever finds this question before the bug is fixed: for my own use I built a utility object with a function to manipulate a "cleanup" list in Collection Variables, but changes wouldn't persist. The workaround for my case is to pass the pm.collectionVariables reference from the Test sandbox at call-time, since that instance seems bound to Collection Variables in the UI.
My Collection's Pre-request Script:
utils = {
addCleanup: (collection, route, id) => {
const list = JSON.parse(collection.get('test_cleanup_list'));
list.push({ route, id, id_field: `${route}id`});
collection.set('test_cleanup_list', JSON.stringify(list));
return list;
}
};
and then from a Test in a Request later in the Run:
utils.addCleanup(pm.collectionVariables, 'account', account.id);
I was able to reproduce a similar behaviour, any chance you did something like this? Where the pre-request script calls a different endpoint than the actual request?
Also, don't know if it can help, in my postman the Forbidden was not uppercase

How to send file from VueJS to API/ExpressJS using axios

Firstly, sorry if my english is bad, i'm not native.
My problem is simple : i already succeded at post some form data from VueJS to ExpressJS API using axios just like that:
axios.post('urlOfMyAPI', this.body).then(response => this.rep = response.data);
The "this.body" thing is an object called body and inside this object, i map all my inputs, like that by example:
<v-textarea v-model='body.text'></v-textarea>
It work well, expressJS can take the data and do the job but when i try to do it with a "v-file-input", all the data inputs go to the API correctly, except the file. When i'm trying to console.log in my API (see the screen under) a random data from input in my API, the data is rendered in my console but the data file is rendered as "undefined".
Have to say one last thing : When i do "console.log(this.body)" in vueJS before the axios post, my file is in the body like expected, so the problem is with axios. I tried to find something on internet but just got some things with a "FormData" object i don't understand and tried to use without success.
My API Code btw, just for example :
exports.Create = (req,res) => {
console.log(req.body.text);
console.log(req.body.file.name);
}
Thanks you if you help me
You have to use formData when submitting files to axios, otherwise, your files won't be available on server-side.
This is a simple method that performs an upload of a file. Please note: if you want to send additional data within your request, you have to add as many formData.append() as you have properties.
uploadAvatar () {
const formData = new FormData()
formData.append('avatar', this.file)
formData.append('other_field', this.otherField)
axios.post('/avatars/upload', formData)
.then((response) => {
console.log(response.data)
})
.catch((e) => {
console.log(e)
})
}
From my experience, if you have a huge form and you want to avoid many formData.append(), the best option is to handle your uploads separately.

Dynamic routing in Next.js gets TypeError: the ‘id’ argument must of type ‘string’. Received null

I’m running into an issue with generating dynamic pages in Next.js. I’m pulling data from Sanity, and I think I’ve got the code right, but every time I try load the page I get a type error - “the ‘id’ argument must be of type string. Received null”. The file path is ‘/post/[slug].js’, so that’s the variable name I’ve used throughout - I’m not sure where id is coming from, or if it’s something extra I need to pass, or if I’m not passing my slug right!
I’ve asked in the Sanity forums, and it doesn’t seem to be an API issue - I’m able to pull data in other parts of the app with no problem. In the console, it seems like the page compiles successfully, but this error comes up when attempting to load it. I’ve tried it with an empty div in the page component, to make sure it’s nothing in the presentation logic, with no luck.
I’ve put the full error message in a gist, and it looks like something with jest or next-server. For the life of me I can’t figure it out!
import client from '../../client’
const Post = ({ post }) => {
...
}
export default Post
export const getStaticPaths = async () => {
const posts = await client.fetch(`*[_type == "blog"]{ slug }`)
const paths = posts.map(post => ({
params: {
slug: post.slug.current
}
}))
return {
paths,
fallback: false }
}
export const getStaticProps = async ({ params }) => {
const post = await client.fetch(`*[_type == "blog" && slug.current == $slug]{ title, date, link, excerpt, body, slug }[0]`, {slug: params.slug})
return {
props: { post }
}
}
UPDATE: this seems to be an issue with either play.js or the configuration it uses - trying in a desktop environment doesn’t result in the same error.
I think the issue is your file name. the name should only be [slug].js, it should be located in pages/post. It should work perfectly when you access the page via the URL http://localhost:xxx/post/pulled-sanity-slug

JavaScript - Promise fulfilled too early?

I created a small sample application using VueJs and created a C# REST API to store and retrieve data in a SQL Server back end.
For testing, I created a simple web page with a form to create a "note". The note is stored by the following function, 'saveData()':
saveData()
{
let promiseStack = [];
var jsondata = JSON.stringify(this.note);
promiseStack.push(this.$http.post('REST_API/note', jsondata));
Promise.all(promiseStack).then(data =>
{
this.$http.get('REST_API/note');
this.$router.push({ name: 'viewnotes', params: { id: data[0].body.id }})
}, error =>
{
console.log(error);
});
}
I tried to use a promise to wait until the 'store' operation in the backend is complete, and issue a GET request to retrieve all notes once the promise is fulfilled.
However, the get request inside the promise doesn't return any data. If I issue the get request manually later one, I retrieve the data that was stored previously.
So I had look into the C# REST API. There are currently two functions: createNote(...), getAllNotes(...). I used a StreamWriter to log to the filesystem when these functions are called, using milisecond precision. What I see is that 'createNote' is called after 'getAllNotes'. So I suspect that the API is working correctly, but something with the way I'm using promises seems to be awfully wrong.
Maybe somebody has a hint?
UPDATE
I know that the GET request doesn't return any data by using the developer toolbar in Chromium. The response is empty
The developer toolbar in the network tab shows that the requests are submitted in the correct order, so the "POST" request is issued first
It seems I found the problem. I had a 'href' tag in my 'Save' link, which triggered an early routing. The intended 'POST' and 'GET' were fired correctly, but there was another 'GET' inbetween somewhere because of the 'href' tag in the link, even though it was empty.
I removed the tag, now it works as intended.

Trying to hit an API with JSON data in REACT

I have just started learning to code in ReactJS and have come to the part where I need to hit an API to get back JSON data.
I am running this on a node server on my local which tries to build it each time I make a change - this helps because it shows me where my errors are. Unfortunately it doesn't mean I know why I am getting an error.
This is my code so far:
import React from 'react';
import './App.css';
var GetUnassignedClients = React.createClass({
unassignedClients: function () {
return $.getJSON('http://localhost/backoffice/?action=unassignedClients.getUnassingedClients')
.then((data) => {
this.setState({resultMe: data.results});
});
},
render: function() {
return (
<div>this.state.resultMe</div>
);
}
});
module.exports = GetUnassignedClients;
I will re-paste the bit that seems to be throwing the error:
return $.getJSON('http://localhost/backoffice/?action=unassignedClients.getUnassingedClients')
.then((data) => {
this.setState({resultMe: data.results});
});
The error seems to be pointing at the $ - when I wrap this all in {} then it points to the full stop (.).
Not sure if I am doing something wrong or missing something.
The $in the $.getJSON is referring to jQuery. Do you have it included in your page? Javascript is trying to parse the dollar sign and can't find it. Other possible solution is to use a separate http library (if you don't need jQuery), such as axiois or fetch for example.
Im not sure, but I thought you would hit in this way
fetch(`http://localhost:8088/api/this/is/an/api/call`)
.then(result=> {
this.setState({items:result.json()});
});
Okay turns out I was trying to use $.getJSON which is JQuery - due to building this on my local using a node server JQuery wasn't included on my local development before the production code was built.
So instead I looked into using fetch that seems to be the go to when coding in react.
I also moved this section into a componentDidMount function so the app would be loaded and then the API call would be made - not that I have a lot of data to load but it's good practice for when you do.
My working code for this section:
componentDidMount () {
fetch("http://localhost/dashboard/?action=unassignedUsers.getUnassingedUsers", {
credentials: 'same-origin'
})
.then(response => response.json())
.then(json => this.setState({data: json}));
}
I also came across a couple issues using fetch - if you need a session available to access said data then you need to specifically pass through the credentials or the API call will re-direct to the login page. At first I saw a status 200 but no data - as it successfully re-directed to the login page, but obviously there was no JSON to access here.

Categories

Resources