【问题标题】:nodejs reachable from internet via react applicationnodejs 可通过 react 应用程序从 Internet 访问
【发布时间】:2022-02-09 06:30:06
【问题描述】:

我有一个在 https 上运行的 react 应用程序和一个运行 localhost:3001 的 nodejs。我的 nodejs 应用程序没有从反应应用程序中捕获数据。 我错过了什么?

server.js (Nodejs)

const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const cors = require('cors');
const app = express();
const Excel = require('exceljs');


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


app.get('/', ()=>{
 console.log('welcome to test')
})
app.post('/api/xcl', (req, res) =>{

const workbook = new Excel.Workbook();
workbook.xlsx.readFile('test.xlsx')
.then(() =>{
const workSheet = workbook.getWorksheet('test');
workSheet.addRow([req.body.fNamn, req.body.eNamn, req.body.oNamn, req.body.ePost, 
req.body.dVal, req.body.kNamn]);
workbook.xlsx.writeFile('test.xlsx');
})
.catch(error => {
console.log(error.message);
});

const PORT = process.env.PORT || 3001
app.listen(PORT, () => console.info(`server has started on ${PORT}`))

app.js (Reactjs)

 axios.post('http://localhost/:3001/api/xcl', data)
        .then(res =>{
            setSent(true)
            console.log(res.data)
        })
        .catch(() => {
            console.log(err=>console.log(err.response.data));
        })

我已经在 package.json 中声明了代理 "proxy": "http://localhost:3001/"

React 应用在 iis 网站上运行 https://test.me:443

【问题讨论】:

  • 不应该是http://localhost:3001/ 而不是http://localhost/:3001/ 吗?
  • 没错,错字...但还是不行!
  • 去掉代理后可以试试吗?

标签: node.js reactjs https axios


【解决方案1】:

如果你设置了代理,你的http请求中不需要写http://localhost:3001,试试

axios.post('/api/xcl', data)
        .then(res =>{
            setSent(true)
            console.log(res.data)
        })
        .catch(() => {
            console.log(err=>console.log(err.response.data));
        })

【讨论】:

  • 我尝试了你的方法但没有成功,我得到 404 请求 URL:domainname.com/api/xcl 请求方法:POST 状态代码:404 远程地址:192.181.211.201:443 推荐人策略:strict-origin-when -跨域
【解决方案2】:

还有另一种方法。 你可以创建你的 axios 实例,并给它 baseURL,然后 http 调用使用该 axios 实例。

import axios from "axios";
const api = axios.create({
 baseURL: "http://localhost:3001",
});

api.post('/api/xcl', data)
        .then(res =>{
            setSent(true)
            console.log(res.data)
        })
        .catch(() => {
            console.log(err=>console.log(err.response.data));
        })

【讨论】:

  • 也不工作,POST localhost:3001/api/xcl net::ERR_CONNECTION_REFUSED...不知何故我的前端(React)无法识别后端(nodejs)连接!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-07
  • 1970-01-01
  • 2015-12-09
  • 1970-01-01
  • 2021-09-18
  • 1970-01-01
相关资源
最近更新 更多