【问题标题】:POST sails server api and react client 500 (Internal Server Error)POST 航行服务器 api 并响应客户端 500(内部服务器错误)
【发布时间】:2019-03-10 11:45:41
【问题描述】:

我使用sails server api 并且我从axios 发布响应但错误500(内部服务器错误)。 这里代码客户端

export default function callApi2(endpoint, method = 'GET', body) {
  
  let headers = { 'content-type': 'application/x-www-form-urlencoded' }
  console.log(body);
  
  return axios({
    method: method,
    url: `${Config.API_URL2}/${endpoint}`,
    data: JSON.stringify(body),
    headers: { 'content-type': 'application/x-www-form-urlencoded' },

  }).catch(err => {
    console.log(err);
  });

这里是代码服务器

    postCommunication: async (req, res)=>{
      res.header('Access-Control-Allow-Origin', '*');
      res.header('Access-Control-Allow-Headers', 'Content-Type');
      res.header('Access-Control-Allow-Methods','GET, POST, PATCH, PUT, DELETE, OPTIONS');

      let newCommunication = req.body;
      console.log(newCommunication);
      console.log(JSON.stringify(newCommunication));


      let resulfCommunication = await Communication.create(JSON.stringify(newCommunication)).fetch();
      return  res.json(resulfCommunication);
    },

【问题讨论】:

  • 请输入有问题的代码而不是图片

标签: reactjs api post sails.js axios


【解决方案1】:

HTTP 状态为 500 表示服务器端发生了崩溃。发生这种情况是因为您在 Axios 代码上传递了错误的内容类型,应该是 "application/json"

export default function callApi2(endpoint, method = 'GET', body) {

  let headers = { 'content-type': 'application/json' }
  console.log(body);

  return axios({
    method: method,
    url: `${Config.API_URL2}/${endpoint}`,
    data: JSON.stringify(body),
    headers: { 'content-type': 'application/json' },
  }).catch(err => {
    console.log(err);
  });

由于您提到 CORS 标头也不是必需的,因此您也可以删除以下代码:

 res.header('Access-Control-Allow-Origin', '*');
 res.header('Access-Control-Allow-Headers', 'Content-Type');
 res.header('Access-Control-Allow-Methods','GET, POST, PATCH, PUT, DELETE, OPTIONS');

欢迎来到 StackOverflow,如果您觉得此答案有帮助,您可以将其标记为答案,以便它可以帮助遇到与您遇到相同问题的人。

【讨论】:

  • 如果我将其设置为“应用程序/json”,则方法获取所有数据错误:对预检请求的响应未通过访问控制检查:没有“Access-Control-Allow-Origin”标头存在请求的资源。 Origin 'localhost:3000' 因此不允许访问。
  • export const actFecthCommunicationReq = ()=>{ return (dispatch)=>{ return callApi2('communication', 'GET', null).then(res =>{ dispatch(actFecthCommunication(res.数据)); }); } }
  • 不,这是代码服务器风帆通信:getAllCommunication: async (req, res)=>{ res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Content-Type'); res.header('Access-Control-Allow-Methods','GET, POST, PATCH, PUT, DELETE, OPTIONS');让通信 = 等待 Communication.find();返回 res.json(通信); },
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-24
相关资源
最近更新 更多