简体   繁体   中英

POST request using axios not bringing a response

Need help on this issue: Working on a project that involves code editor and evaluating the code from the USER.

Created a route and a function on my backend (Express) where the function takes the user written code, evaluates and return its value.

Post request is being made using axios from the Frontend(REACT) to backend for the user code to be evaulated and send the response back to frontend.

What i have accomplished: send the user code to backend via post request. code is eval in the backend using sandbox.

What i am having issues with? sending the response back to the frontend. The post req does not bring back a response.

below is the code: any thoughts / feedback?

BACKEND:

const express = require('express');
const codeRoutes = express.Router();
const codeHelper = require('../services/code/code-helper');

codeRoutes.post('/', codeHelper.codeEval, (req, res) => {res.json({
    data: res.result
 }) 
});

module.exports = codeRoutes;

HELPER FUNCTION:

const vm = require('vm');


let codeEval = (req, res) => {
   let result;
   let code = req.body.code;
   const sandbox = {};
   vm.createContext(sandbox);
   result = vm.runInContext(code, sandbox);
   console.log(result); // this does console.log in the terminal
   return result;
 }

 module.exports = { codeEval };

FRONTEND:

 handleExecuteCode = (code) => {    
 axios.post('/code', {
  code: code,
}).then(res => {
  console.log('frontend received--->', res)
}).catch(err => console.log(err));
}

<button onClick={() => 
this.handleExecuteCode(this.state.code)}>EXECUTE</button>

actually just figured it out. My setup is correct. I was not using and calling next() in my helper function thus it was not returning anything. I just tested and it works. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM