node.js - 向 glitch.me 服务器发出跨域请求

标签 node.js cors glitch-framework

我在 glitch.me 上创建了一个服务器,我正在尝试从服务器提供数据,但出现以下错误。 localhost/:1 访问 ' https://clem-quote-server.glitch.me/quotes 获取'来自原点'http://localhost:3000 ' 已被 CORS 策略阻止:

No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

不太确定如何解决这个问题

import React, {Component} from "react"

class quotes extends Component {
    constructor(props) {
        super(props);
        this.state = {
            error: null,
            isLoaded: false,
            quotes: quotes
        };
    }

componentDidMount() {
    fetch("https://clem-quote-server.glitch.me/quotes")
      .then(res => res.json())
      .then(
        (result) => {
            this.setState({
            isLoaded: true,
              quotes: result.quotes
          });
        },
        error => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      );
}

    render() {
        const { error, isLoaded, quotes } = this.state;
        if (error) {
            return <div>Error: {error.message}</div>;
        } else if (!isLoaded) {
            return <div>Loading...</div>;
        } else {
            return (
              <ul>
                {quotes.map(quote => {
                    return quote;

                }  
                )}
              </ul>
            );
        }
    }
}       
    export default quotes;

我希望能够在每次加载页面时显示数组列表中的一个对象

最佳答案

它失败是因为 CORS,当服务器和客户端处理不同的域时必须包含 CORS。

CORS 包含在 header 中。

以下是在 React 应用程序中启用 corse 的方法:

https://facebook.github.io/create-react-app/docs/proxying-api-requests-in-development

CORS 信息:

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

关于node.js - 向 glitch.me 服务器发出跨域请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56135462/

相关文章:

node.js - 为什么我在 Web 服务器上收到代理错误,但在本地主机上却没有?

node.js - Mongoose findById 没有返回所有字段

node.js - Elasticsearch找不到最近插入的数据

node.js - NodeJs 中的 fs 转储等价物?

javascript - "FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory"与 npm 搜索

javascript - 处理响应 - SyntaxError : Unexpected end of input when using mode: 'no-cors'

dart - 如何创建/添加向每个请求添加默认 header 的中间件

jquery - 为什么即使缺少 Access-Control-Allow-Headers,CORS 请求也会成功?