首页 > 解决方案 > 从 Gatsby JS 制作 Axios 发布 Req

问题描述

我正在尝试从我的组件状态中获取数据,然后将其发送到 REST api。我在 on submit 函数中创建了 axios post req,但是我知道这在 gatsby 中不起作用。当我从 Gatsby 的 onSubmit 函数发出请求时,我的 res.data 是“这个应用程序最适合 Javascript”。我想知道我可以从 Gatsby 发出发布请求的最佳方式是什么,以便我可以从组件的状态中传递数据。我一直在考虑将其用作我的 gatsby-node.js 文件,但是我不确定如何在其中获取组件的状态数据,以便可以在 post req 中使用它。谢谢。

onSubmit 函数

    //submits answers to backend
   Submit = () => {
    let {answers} = this.state
    axios
      .post("/done", answers)
      .then(res => this.setState({results:res.data,resultsStatus:true}))
      .catch(
        err => console.log(err)
      );
  };

要触发提交功能,我有一个加载 gif 弹出窗口 4 秒钟,然后我触发提交功能。内容请求是组件返回的jsx

 contentQuest = (
            <div className = 'results-loading'>
            Loading Results!
    <img src={require('./images/loading.gif')} className='results-loading-gif'/>
  </h2>
            </div>
          );
          setTimeout(() => {
            this.Submit()
          },4000)

盖茨比-node.js


// You can delete this file if you're not using it
const axios = require('axios');
const crypto = require('crypto');

exports.sourceNodes = async ({ boundActionCreators }) => {
  const { createNode } = boundActionCreators;

  // fetch raw data from the randomuser api
//Here I'm trying to change it to axios.post and grab component's state data
//not sure how to
  const fetchRandomUser = () => axios.get(`https://randomuser.me/api/?results=500`);
  // await for results
  const res = await fetchRandomUser();

  // map into these results and create nodes
  res.data.results.map((user, i) => {
    // Create your node object
    const userNode = {
      // Required fields
      id: `${i}`,
      parent: `__SOURCE__`,
      internal: {
        type: `RandomUser`, // name of the graphQL query --> allRandomUser {}
        // contentDigest will be added just after
        // but it is required
      },
      children: [],

      // Other fields that you want to query with graphQl
      gender: user.gender,
      name: {
        title: user.name.title,
        first: user.name.first,
        last: user.name.last,
      },
      picture: {
        large: user.picture.large,
        medium: user.picture.medium,
        thumbnail: user.picture.thumbnail,
      }
      // etc...
    }

    // Get content digest of node. (Required field)
    const contentDigest = crypto
      .createHash(`md5`)
      .update(JSON.stringify(userNode))
      .digest(`hex`);
    // add it to userNode
    userNode.internal.contentDigest = contentDigest;

    // Create node with the gatsby createNode() API
    createNode(userNode);
  });

  return;
}

编辑:我尝试将我的发布请求更改为此

fetch('http://localhost:5000/api/done', {
    method: 'POST',
    body: JSON.stringify(answers),
    headers : { 
      'Content-Type': 'application/json',
      'Accept': 'application/json'
     }
  }) .then(res => {
      return res.json()})
      .then(res => console.log(res))
      .catch(
        err => {
          console.log(err)}
      );
  };

现在我的控制台中有这条消息:

CORS 策略已阻止从源“ http: //localhost:5000/api//done ”获取从“ http://localhost:8000 ”获取的访问权限:对预检请求的响应未通过访问控制检查:否“ Access-Control-Allow-Origin' 标头出现在请求的资源上。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

标签: javascriptreactjsrestaxiosgatsby

解决方案


所以事实证明我需要将它包含在我的服务器文件中。

app.use(function(req, res, next) {
  res.header(`Access-Control-Allow-Origin`, `http://localhost:9000`)
  res.header(`Access-Control-Allow-Credentials`, true)
  res.header(
    `Access-Control-Allow-Headers`,
    `Origin, X-Requested-With, Content-Type, Accept`
  )
  next();
});

推荐阅读