本文介绍了表示服务器的Javascript提取(POST)失败.服务器未从JS接收请求,但从Postman接收请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MRE ->

测试已发送被打印到我的节点服务器的控制台中

但是,如果我从我的反应形式发送请求,则 test send 不会打印到控制台,但是获取请求的 catch 块将被执行,并且 err 会打印到我的react应用程序的控制台上,然后显示 {} .

我想知道为什么我的POST请求无法正常工作并且服务器无法接收到


以下是当有人单击在react中创建的表单的提交按钮时调用的函数

提交表单时调用的功能

  nodeUrl ='https://localhost:6060?'const SubmitData = async()=>{fetch(nodeUrl,{方法:"POST",标头:{'Accept':'application/json','Content-Type':'application/json',},正文:JSON.stringify({'test':'test'})}).then((res)=> {警报('then')}).catch((err)=> {警报('err')警报(JSON.stringify(err))})}} 

这是我使用 node server.js

运行的服务器

server.js

  server.post('/',function(req,res){console.log('测试已发送')mailer.messages().send(要求正文).then((mes)=> {console.log(mes)res.json({消息:感谢您的消息.我们的服务团队已收到通知,并将尽快与您联系."})}).catch(err => {console.log(err)res.json(err);})}); 
解决方案

此处的不可抗力问题是由于 CORS .可以使用 CORS支持来解决此问题.请记住,只有开发模式才能使用此功能(请参见以下代码).

但是,根据邮递员的快照和提供的GitHub存储库,来自前端的请求应为 multipart/form-data 类型.因此,前端代码看起来像这样

  const nodeUrl ="http://localhost:6060/";const SubmitData = async()=>{//创建一个FormData对象const formData = new FormData();formData.append('form','example@email.com');formData.append('to','example@email.com');//此自动在请求中添加'multipart/form-data'+ HASH标头fetch(nodeUrl,{方法:"POST",正文:formData}).then(res => {console.log(res);}).catch(err => {console.log('错误-',err);});}; 

要在ExpressJS中处理 multipart/form-data 请求,您需要一个插件马尔特.

  const express = require('express');const bodyParser = require('body-parser');const multer = require('multer');//用于多部分"类型的请求const server = express();const upload = multer();//在开发模式下允许CORS请求如果(process.env.NODE_ENV ==='开发'){//服务器运行命令-"NODE_ENV =开发节点server.js"const cors = require('cors');server.use(cors());}server.use(bodyParser.json());server.use(bodyParser.urlencoded({extended:true})));//使用Multer中间件形式提取"FormData"有效负载server.post('/',upload.none(),function(req,res){console.log('Received body',req.body);...//其他代码}); 

策略2(纯JSON)-

如果这种多部分/表单数据"策略不是故意的,而您只想发送简单的JSON,请使用以下代码-

在前端,以-

触发API请求

  fetch(nodeUrl,{方法:"POST",标头:{'Content-Type':'application/json',//需要定义},正文:JSON.stringify({from:'some@email.com',to:'other@email.com'})}) 

在服务器中,只需忽略与Multer相关的代码,而仅将您的API保持为-

  server.post('/',function(req,res){console.log('Received body',req.body);...//其他代码}); 

MRE -> node-server : react app


When I send a POST request using Postman, I get the expected result. This is the request that I am sending using Postman

and test sent gets printed to the console of my node server

If I send a request from my react form however, test sent does not print to the console, but the catch block of my fetch request get's executed and err is printed to the console of my react app, followed by {}.

I would like to know why my POST request is not working and is not getting received by the server


Below is the function that I call when someone clicks the submission button of my form created in react

Function called on form submission

nodeUrl = 'https://localhost:6060?'

const submitData = async () => {

    fetch(nodeUrl, {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({'test': 'test'})
    }).then((res) => {
      alert('then')
    }).catch((err) => {
      alert('err')
      alert(JSON.stringify(err))
    })
  }
}

This is the server that I run using node server.js

server.js

server.post('/', function(req, res) {
    console.log('test sent')
    mailer.messages().send(req.body)
    .then((mes) => {
        console.log(mes)
        res.json({ message: 'Thanks for your message. Our service team has been notified and will get back to you shortly.' })
    }).catch(err => {
        console.log(err)
        res.json(err);
    })
});
解决方案

The majour issue here is due to CORS. CORS support can be used to overcome this. Just keep in mind to have this only for development mode(see below codes).

But, as per the Postman's snapshot and provided GitHub repositories, the request from Front-end should be of multipart/form-data type. Thus, the Front-end code would look like this

const nodeUrl = "http://localhost:6060/";

const submitData = async () => {
  // create a FormData object
  const formData = new FormData();
  formData.append('form', 'example@email.com');
  formData.append('to', 'example@email.com');

  // this auto adds 'multipart/form-data' + HASH header in the request
  fetch(nodeUrl, {
    method: "POST",
    body: formData
  })
    .then(res => {
      console.log(res);
    }).catch(err => {
      console.log('Error -', err);
    });
};

To handle multipart/form-data request in the ExpressJS, you need a plugin Multer.

const express = require('express');
const bodyParser = require('body-parser');
const multer  = require('multer'); // for 'multipart' type request
const server = express();
const upload = multer();

// allow CORS requests in development mode
if (process.env.NODE_ENV === 'development') {
  // Server run command - "NODE_ENV=development node server.js"
  const cors = require('cors');
  server.use(cors());
}

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

// using Multer middleware form extracting 'FormData' payload
server.post('/', upload.none(), function(req, res) {
  console.log('Received body', req.body);
  ... // other codes
});

Strategy 2(plain JSON) -

If that 'multipart/form-data' strategy was unintentional and you just want to send simple JSON, use below codes -

In Front-end, trigger API request as -

fetch(nodeUrl, {
  method: "POST",
  headers: {
    'Content-Type': 'application/json', // this needs to be defined
  },
  body: JSON.stringify({ from: 'some@email.com', to: 'other@email.com' })
})

In server, just ignore codes related to Multer and only keep your API as -

server.post('/', function(req, res) {
  console.log('Received body', req.body);
  ... // other codes
});

这篇关于表示服务器的Javascript提取(POST)失败.服务器未从JS接收请求,但从Postman接收请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 17:32
查看更多