问题描述
我需要你的帮助。
我的问题如下:
- 我从快速服务器调用 API
- 要调用 api,我需要来自客户端的 url。
- 我在服务器端收到了 url
- 我调用 api 并获取数据。
- 我想通过 app.post 发送数据
- 发送数据是因为在路由上我看到了数据 ('/client_data');
- 我在客户端获取数据(在 formHandler.js 中)
- 我在 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',res)=>{
res.send(json);
})
} catch (err) {
console.error("error");
}
});
} getData();
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)