我需要你的帮助。
我的问题如下:
这就是我遇到的问题。
代码如下:
客户端:
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();