Get external api with axios and req body to url for search and ajax NodeJS express

Viewed 218

I use node.js expess with MVC pattern and use axios for get json url. The all logic request api i wrote it in Controller , I try to create some get api with axios like this.

this my chartController.js , it's some logic for get json from url with req.body.symbol (it's just symbol of stock from user submitted input form , I want to get that symbol to my axios get url in code below in const chartChartPage )

'use strict';

const axios = require('axios');

const request = require('request');

/* For Get my Api Token Data */
const dataTokens = require('../config/apitokens');

const chartChartPage = async (req,res) => {
    try {
        const symbol = req.body.symbol;
        const url = `https://${dataTokens.sandbox}.iexapis.com/stable/stock/${symbol}/chart/1m?token=${dataTokens.tokens}`;
        const fetchData = await axios.get(url);
        res.status(200).json(fetchData.data);
        
    }
    catch (error){
        res.status(400).send(error.message);
    }
}



module.exports = {
    chartPage, 
    chartChartPage

   
   
}

Now, i have to added some routes in my chart.js i think i should add router.post('/', chartChartPage) for get that symbol in input when user submitted Maybe i'm wrong.

var express = require('express');

var router = express.Router();

var {chartPage , chartChartPage} = require('../controllers/chartControllers');


router.get('/', chartPage);


router.post('/', chartChartPage);






module.exports = router;

and in my chartChartPage.js (it's just js file for my template) and use ajax to get that data from url above (with chartChartPage) to get data for build chart stock and try to console.log that data but that's not work in console

$(function(){
    chartChartPage();
});

const chartChartPage = async () => {
    await $.ajax({
        url: '/chart',
        type: 'POST',
        dataType: 'json',
        success: (response) => {   
            if (response != null) {
                console.log(response);
            }
        }, 
        error: (err) => {
            console.log(err);
            
        }
    });
}

and when i submitted form i got that all json data in my page, but i want when submitted it's render to same page and work in console.log in ajax get url above. How can i fix.? enter image description here

0 Answers
Related