Home > Blockchain >  How to get this data sent to from index.js to script.js using express (Node JS)?
How to get this data sent to from index.js to script.js using express (Node JS)?

Time:05-25

Beginner here...so bear with me :)

I'm getting this dataset in the console, but I can't wrap my head around getting it sent to the client side...

const { response } = require('express');
const express = require('express');
const app = express();
const port = 3000;

app.use(express.static('public'));

app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`));

const translate = require('sdapi').default.translate;
translate('hablar').then(console.log);

This is the result I get:

[
  {
    word: 'hablar',
    lang: 'es',
    gender: undefined,
    context: 'to articulate words',
    meaning: 'to speak',
    part: 'intransitive verb',
    examples: [ [Object] ],
    regions: []
  }]

I've tried wraping it into a app.get('/translation', async (req, res) => {}) but it doesn't work.

Appreciate your time/attention.

CodePudding user response:

app.get('/translate/:word', async (req, res) => {
  const {
    params: { word },
  } = req; // same as const word = req.params.word
  const translatedWord = await translate(word); // same as .then

  return res.status(200).json({ translatedResponse: translatedWord });
});

To activate this you have to send http get request to whateverip:port/translate/<WORD_TO_TRANSLATE_INPUT>

You can send http requests with axios, curl, or fetch and your browser's terminal thouhg the last one isn't always optimal solution.

CodePudding user response:

I think you want to check your controller and sed data to it so the first step that u must do to install body-parser with npm i body-parser

then use it like

const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

now u can receive and store your data on request.

then learn about the request (https://expressjs.com/en/guide/routing.html)

then u can send a request to your server with postman or Axios or curl and something else .

I hope to solve your question.

  • Related