3

I'm trying to send user data from Nuxt.js using Axios via a POST request. The data is already provided via a Javascript cdn function that returns an object with user parameters, so I wouldn't want to use a form since I'm forwarding the user data I received as JSON.

I wanted to know if the method I'm using is the right way of doing this? I need to send the user information in order to send a query in the backend to an external API (requiring a token from both the front and the back end, e.g., user token and app token).

Here is my current iteration:

    <script>
export default {
    head (){
        return {
            __dangerouslyDisableSanitizers: ['script'],
            script: [
                {
                    hid: 'platform-api',
                    src: "https://cdn-sample.app.com/api",
                    type: 'text/javascript',
                    defer: true
                },
            ]
        }
    },
    computed: {
        // Change user token parameter according to docs
        // Add Neccessary parameters
        auth_token: {
            get(){
               let userdata = getPlatformContext();
               this.$store.state.user.auth_token = userdata.auth_token;
               return this.$store.state.user.auth_token;
            },
            set(value){
                    this.$store.commit("item/storeAuthToken", value)
                }
        },
        // Additional parameters omitted as they extract each parameter in the same way
        // as above.
    methods: {
        // I tried to test it by sending just the user token by clicking a button
        async sendUserToken(auth_token) {
            await this.$axios.post(this.$config.baseURL, user.auth_token);
        },
        // Then i wanted instead to try and send the whole json dict of user data to 
        // backend and sort the data over in fastapi according to what i need.
        async sendUserData(user) {
            await this.$axios.post(this.$config.baseURL, user);
        }
        
    },
    
}

</script>

So, if I wanted to send the user data as a POST request in JSON format, not as a form, what would be the best way to do this?

Chris
  • 18,724
  • 6
  • 46
  • 80
Solly
  • 43
  • 5

1 Answers1

1

Below is an example on how to send JSON data using Axios to a FastAPI backend. The data should be send as a stringified JSON. One can do that using the JSON.stringify() function, which is used to convert a JavaScript object to a JSON string. Related answers can be found here (Option 2) and here (Methods 3 & 4).

app.py

from fastapi import FastAPI, Request, Body
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel

app = FastAPI()
templates = Jinja2Templates(directory="templates")

class User(BaseModel):
    username: str
    address: str
    
@app.get("/")
def main(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})
  
@app.post("/submit")
def main(user: User):
    return user

Note: If one wouldn't like using Pydantic models for posting JSON data, they could instead use Body fields, as described in the documentation here and here. If a single Body parameter is expected by the endpoint, one should use the special Body parameter embed, as demonstrated in this and this answer.

templates/index.html

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.27.2/axios.min.js"></script>
<script type="text/javascript">
function uploadJSONdata() {
    axios({
            method: 'post',
            url: '/submit',
            data: JSON.stringify({"username": "some name", "address": "some address"}),
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
        })
        .then(response => {
            console.log(response);
            document.getElementById("p1").innerHTML = JSON.stringify(response.data);
        })
        .catch(error => {
            console.error(error);
        });
}
</script>
<p id="p1"></p>
<input type="button" value="submit" onclick="uploadJSONdata()">

Above is the client side (frontend), which uses Axios to POST the JSON data. Similar approach to the above should be used with the JavaScript framework/library (i.e., Nuxt.js) you are using. For example:

this.$axios.post('/submit', {
    username: 'some name',
    address: 'some address'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
Chris
  • 18,724
  • 6
  • 46
  • 80
  • 1
    Thank you, this helped me figure out how to implement this. I've decided to store state of a function with the required info and then post the user info to backend. – Solly Jul 28 '22 at 01:40