将数据从服务器发送到客户端(节点 JS + webpack

时间:2021-03-06 20:21:12

标签: javascript node.js post webpack get

我需要你的帮助。

我的问题如下:

  1. 我从快速服务器调用 API
  2. 要调用 api,我需要来自客户端的 url。
  3. 我在服务器端收到了 url
  4. 我调用 api 并获取数据。
  5. 我想通过 app.post 发送数据
  6. 发送数据是因为在路由上我看到了数据 ('/client_data');
  7. 我在客户端获取数据(在 formHandler.js 中)
  8. 我在 console.log 中查看数据,但什么也没出现...

这就是我遇到的问题。

代码如下:

客户端:

function handleSubmit(event) {
event.preventDefault()
// get the url from the users
let user_url = document.getElementById('url').value;
console.log(user_url);

// send the url to the server for the API CALL
fetch("/server", {
    method: "POST",
    credentials: "same-origin",
    headers: {
        "Content-Type": "application/json",
    },
    body: JSON.stringify({
        user_url
    }),
});


//  sendData("/server", user_url);
 //get the data of the API send by the server
const url = "/client_data";
async function receiveData() {
  const serverResponse = await fetch(`http://localhost:3000${url}`);
  const convertToJson = await serverResponse.json();
  console.log(convertToJson);
  return convertToJson;
}
receiveData();} export {handleSubmit}

服务器端:

// require express to run the server
const path = require('path');
const express = require("express");
const port = 3000;
const dotenv = require('dotenv');
dotenv.config();
const fetch = require('node-fetch');

// instance of the app
const app = express();

// require dependencies

const cors = require("cors");
const bodyParser = require("body-parser");

// cross origin allowance

app.use(cors());

// middleware

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));

//main project folder
app.use(express.static("dist"));

// server listening

app.listen(port, () => {
    console.log(`The server is working on port number ${port}`);
});

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname + '/dist/index.html'))
});

async function getData() {

// get the url send by the client
let url_from_client = "";
app.post("/server", async (req,res)=>{
    url_from_client = req.body.user_url;
    res.send("The data has been received");
    const url_api = "https://api.meaningcloud.com/sentiment-2.1";
    const key_api = process.env.KEY_API;
    const response = await fetch(`${url_api}?key=${key_api}&lang=fr&url=${url_from_client}`);
    try{
        const json = await response.json();
        console.log(json);
        app.get('/client_data', (req,res)=>{
            res.send(json);
        })
    } catch (err) {
        console.error("error");
    }
});

} getData();

0 个答案:

没有答案