0

I am trying to pass multiple parameters to my api (Koa) via URL (from ReactJS using Axios) to post data to my db. This code is working, but I am wondering if there is an easier way to pass data instead of typing out each value to insert into the database?

I am adding an advising time to my db as such:

In ReactJs file:

axios.post(`/Advising/AddTime/${idValue}/${dayValue}/${startValue}/${endValue}/${timeValue}`) 

In my Koa (node.js) file:

AdvisingRouter.post('/AddTime/:id/:day/:starttime/:endtime/:timeblock', AdvisingController.addTimes, (err) => console.log("routers.js: AdvisingRouter error:", err)); 

And lastly my controller:

class AdvisingController { async addTimes(ctx) { return new Promise((resolve, reject) => { let query = "INSERT INTO AdvisingTimes (id, Day, StartTime, EndTime, TimeBlock) VALUES (?, ?, ?, ?, ?);"; console.log('About to run this query.', query); dbConnection.query( { sql: query, values: [ctx.params.id, ctx.params.day, ctx.params.starttime, ctx.params.endtime, ctx.params.timeblock] }, (error) => { if (error) { return reject(error); } } ) }).catch(err => { ctx.body = { status: "Failed", error: err, user: null }; }); } 
1

2 Answers 2

3

Given you are using POST then you can always send the data as part of the payload

axios.post('/Advising/AddTime/', { id, day, starttime, endtime, timeblock }); 

Then at the backend you can access the data via ctx.request.body

Note - you would need to include a body parser like koa-body

Sign up to request clarification or add additional context in comments.

Comments

0

Helpful function that I use:

const insertParams = (url, params) => { // url is string, params is object let paramUrl = url; const copyParams = Object.assign({}, params); Object.keys(copyParams).forEach(key => { const currentParam = copyParams[key]; if (paramUrl.includes(key)) delete copyParams[key]; paramUrl = paramUrl.replace(`:${key}`, currentParam); }); return paramUrl; }; 

And for your case simply call insertParams:

const url = 'http://your.url.com/'; const params = { id: 'id123', day: 'friday', starttime: new Date(), endtime: new Date(), timeblock: 'timeblock' }; const urlWithParams = insertParams(url, params); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.