简体   繁体   English

CORS header 'Access-Control-Allow-Origin' 缺少反应

[英]CORS header ‘Access-Control-Allow-Origin’ missing REACT

I am building a react application on top of spring boot.我正在 spring 引导之上构建一个反应应用程序。 I have been getting these errors on my browser when I try to make a put request to localhost:8080当我尝试向 localhost:8080 发出 put 请求时,我的浏览器上出现了这些错误

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/products.跨域请求被阻止:同源策略不允许读取位于 http://localhost:8080/products 的远程资源。 (Reason: CORS header 'Access-Control-Allow-Origin' missing). (原因:缺少 CORS header 'Access-Control-Allow-Origin')。

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/products.跨域请求被阻止:同源策略不允许读取位于 http://localhost:8080/products 的远程资源。 (Reason: CORS request did not succeed) (原因:CORS 请求没有成功)

I have set up @CrossOrigin on my server-side for localhost 3000.我已经在我的服务器端为 localhost 3000 设置了@CrossOrigin。

Been trying to fix this for a while by adding headers, proxies and even using the firefox CORS everywhere.一段时间以来一直试图通过添加标头、代理甚至在各处使用 firefox CORS 来解决此问题。 Nothing seems to be working.似乎没有任何工作。

Please see my front end code below请在下面查看我的前端代码

import React, { Component } from "react";
import { Card, Form, Button } from "react-bootstrap";
import axios from "axios";
import Toasting from "./Toasting";
export default class AddProducts extends Component {
  constructor(props) {
    super(props);
    this.state = this.startState;
    this.state.toast = false;
    this.productChange = this.productChange.bind(this);
    this.submitProduct = this.submitProduct.bind(this);
    var config = {
            headers: {'Access-Control-Allow-Origin': '*'}
        };
  }

  startState = { id: "", name: "", brand: "", made: "", price: "" };

  componentDidMount() {
    const productId = this.props.match.params.id;
    if (productId) {
      this.findProductById(productId);
    }
  }

  findProductById = (productId) => {
    axios
      .get("http://localhost:8080/products/" + productId)
      .then((response) => {
        if (response.data != null) {
          this.setState({
            id: response.data.id,
            name: response.data.name,
            brand: response.data.brand,
            made: response.data.madein,
            price: response.data.price,
          });
        }
      })
      .catch((error) => {
        console.error("Error has been caught: " + error);
        console.log(error);
      });
  };

  reset = () => {
    this.setState(() => this.startState);
  };

  submitProduct = (event) => {
    //Prevent default submit action
    event.preventDefault();

    const product = {
      id: this.state.id,
      name: this.state.name,
      brand: this.state.brand,
      madein: this.state.made,
      price: this.state.price,
    };


    axios.post("http://localhost:8080/products", product)

    .then((response) => {
      if (response.data != null) {

        this.setState({ toast: true });
        setTimeout(() => this.setState({ toast: false }), 3000);
      } else {
        this.setState({ toast: false });
      }
    });
    this.setState(this.startState);
  };

  productChange = (event) => {
    this.setState({
      [event.target.name]: event.target.value,
    });
  };

  productList = () => {
    return this.props.history.push("/");
  };

  updateProduct = event => {
    //Prevent default submit action
    event.preventDefault();

    const product = {
      id: this.state.id,
      name: this.state.name,
      brand: this.state.brand,
      madein: this.state.made,
      price: this.state.price,
    };

    ***************THIS IS WHERE THE ERROR IS**********************************************
    axios.put("http://localhost:8080/products", product, this.config).then((response) => {

      if(response.data != null) {
        this.setState({ toast: true });
        setTimeout(() => this.setState({ toast: false }), 3000);
        setTimeout(() => this.productList(), 3000);
      } else {
        this.setState({ toast: false });
      }
    });
    this.setState(this.startState);
  };

  render() {
    const { name, brand, made, price } = this.state;
    return (
      <div>
        <div style={{ display: this.state.toast ? "block" : "none" }}>
          <Toasting
            toast={this.state.toast}
            message={"Product has been successfully saved!!!"}
            type={"success"}
          />
        </div>

        <Card className={"border border-dark bg-dark text-white"}>
          <Card.Header align="center">
            {" "}
            {this.state.id ? "Update a Product" : "Add a Product"}
          </Card.Header>
          <Form
            onSubmit={this.state.id ? this.updateProduct : this.submitProduct}
            id="productFormId"
            onReset={this.reset}
          >
            <Card.Body>
              <Form.Row>
                <Form.Group controlId="formGridName">
                  <Form.Label>Product Name</Form.Label>
                  <Form.Control
                    required
                    autoComplete="off"
                    type="text"
                    name="name"
                    value={name}
                    onChange={this.productChange}
                    required
                    autoComplete="off"
                    className={"bg-dark text-white"}
                    placeholder="Enter Product Name"
                  />
                </Form.Group>
              </Form.Row>
              <Form.Row>
                <Form.Group controlId="formGridBrand">
                  <Form.Label>Brand</Form.Label>
                  <Form.Control
                    required
                    autoComplete="off"
                    type="text"
                    name="brand"
                    value={brand}
                    onChange={this.productChange}
                    className={"bg-dark text-white"}
                    placeholder="Enter Brand Name"
                  />
                </Form.Group>
              </Form.Row>
              <Form.Row>
                <Form.Group controlId="formGridMade">
                  <Form.Label>Made</Form.Label>
                  <Form.Control
                    required
                    autoComplete="off"
                    type="text"
                    name="made"
                    value={made}
                    onChange={this.productChange}
                    className={"bg-dark text-white"}
                    placeholder="Made in"
                  />
                </Form.Group>
              </Form.Row>
              <Form.Row>
                <Form.Group controlId="formGridPrice">
                  <Form.Label>Price</Form.Label>
                  <Form.Control
                    required
                    autoComplete="off"
                    type="text"
                    name="price"
                    value={price}
                    onChange={this.productChange}
                    className={"bg-dark text-white"}
                    placeholder="Product Price"
                  />
                </Form.Group>
              </Form.Row>
            </Card.Body>
            <Card.Footer>
              <Button size="sm" variant="success" type="submit">
                {this.state.id ? "Update" : "Submit"}
              </Button>{" "}
              <Button size="sm" variant="info" type="reset">
                Undo
              </Button>{" "}
              <Button
                size="sm"
                variant="info"
                type="button"
                onClick={this.productList.bind()}
              >
                Products
              </Button>
            </Card.Footer>
          </Form>
        </Card>
      </div>
    );
  }
}

Please see my product Controller class server-side below请在下面查看我的产品 Controller class 服务器端

package ie.sw.spring;

import java.util.List;
import java.util.NoSuchElementException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.CrossOrigin;


@RestController
@CrossOrigin("http://localhost:3000")
public class ProductController {

    @Autowired
    private ProductService service;

    @GetMapping("/products")
    public List<Product> list() {
        return service.listAll();
    }

    // Get products by their id
    @GetMapping("/products/{id}")
    public ResponseEntity<Product> get(@PathVariable Long id) {
        try {

            Product product = service.get(id);
            return new ResponseEntity<Product>(product, HttpStatus.OK);

        } catch (NoSuchElementException e) {

            return new ResponseEntity<Product>(HttpStatus.NOT_FOUND);
        }

    }

    // Handle post requests
    @PostMapping("/products")
    public void add(@RequestBody Product product) {
        service.save(product);
    }

    // Update a product
    @PutMapping("/products/{id}")
    public ResponseEntity<?> update(@RequestBody Product product, @PathVariable Long id) {
        try {
            Product existProduct = service.get(id);
            service.save(product);
            return new ResponseEntity<>(HttpStatus.OK);
        } catch (NoSuchElementException e) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }

    }
    
    @DeleteMapping("/products/{id}")
    public void delete(@PathVariable Long id) {
        service.delete(id);
    }

}
***************THIS IS WHERE THE ERROR IS**********************************************
    axios.put("http://localhost:8080/products", product, this.config).then((response) => {
       ...
    }

    @PutMapping("/products/{id}")
    public ResponseEntity<?> update(@RequestBody Product product, @PathVariable Long id) {
       ...
    }

I think you have missed the path variable while creating the request with axios.put .我认为您在使用axios.put创建请求时错过了路径变量。 Either you should remove the @PathVariable Long id or you have to pass the id in the request.您应该删除@PathVariable Long id ,或者您必须在请求中传递 id。

Option 1

axios.put("http://localhost:8080/products/" + productId, product, this.config).then((response) => {
   ...
}

@PutMapping("/products/{id}")
public ResponseEntity<?> update(@RequestBody Product product, @PathVariable Long id) {
   ...
}  

Option 2

axios.put("http://localhost:8080/products", product, this.config).then((response) => {
   ...
}

@PutMapping("/products")
public ResponseEntity<?> update(@RequestBody Product product) {
   ...
}  

Also, change the @CrossOrigin as follow此外,更改@CrossOrigin 如下

@CrossOrigin(origins = "http://localhost:3000", methods = {RequestMethod.OPTIONS, RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE}, allowedHeaders = "*", allowCredentials = "true")

You may also have look here你可能也看过这里

Did you tried to add "proxy": "http://localhost:8080" to the package.json file.您是否尝试将"proxy": "http://localhost:8080"添加到package.json文件。 That helped me.这对我有帮助。 I had the same problem.我有同样的问题。

@CrossOrigin("http://localhost:3000") @CrossOrigin("http://localhost:3000")

is wrong, try错了,试试

@CrossOrigin("http://localhost:8080") @CrossOrigin("http://localhost:8080")

I have set up @CrossOrigin on my server-side for localhost 3000.我已经在我的服务器端为 localhost 3000 设置了@CrossOrigin。

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080 /products.跨域请求被阻止:同源策略不允许读取位于http://localhost:8080 /products 的远程资源。 (Reason: CORS header 'Access-Control-Allow-Origin' missing). (原因:缺少 CORS header 'Access-Control-Allow-Origin')。

Your error is for localhost:8080 .您的错误是针对localhost:8080的。

Solutions:解决方案:

  1. Set in your server-side localhost:8080 .在您的服务器端localhost:8080中设置。
  2. You could, which is not recommended, set * in your server-side, it sets all urls.您可以(不推荐)在服务器端设置* ,它会设置所有 url。
  3. Or the other solution is to change your port in your front app to the one you've set in your back.或者另一种解决方案是将前端应用程序中的端口更改为您在后面设置的端口。

If you're just trying to run locally have you tried the chrome addon?如果您只是想在本地运行,您是否尝试过 chrome 插件?

https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf

Two possible answers:两个可能的答案:

  1. Configure cors in you WebConfig file.在 WebConfig 文件中配置 cors。 From spring Documentation来自 spring 文档

Your method would be like:你的方法是这样的:

public void addCorsMappings(CorsRegistry registry) {

    registry.addMapping("/**")
        .allowedOrigins("https://localhost:3000/**")
        .allowedMethods("PUT", "DELETE","GET","POST");
    // Add more mappings...
}
  1. For testing, change your @CrossOrigin to all origins:为了进行测试,请将您的 @CrossOrigin 更改为所有来源:

    @CrossOrigin(origins =*) @CrossOrigin(起源 =*)

If it works, then it's just a detail somewhere.如果它有效,那么它只是某个地方的一个细节。 Can you test it and tell us?你能测试一下并告诉我们吗?

Looking at the documentation, they always leave explicit 'origins="address"'.查看文档,他们总是留下明确的'origins="address"'。 In your cause it would be:在您的事业中,它将是:

  @CrossOrigin(origins ="http://localhost:3000")

Use利用

@CrossOrigin(origins = "http://localhost:3000")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 反应和 Django CORS header 'Access-Control-Allow-Origin' 缺失 - React and Django CORS header ‘Access-Control-Allow-Origin’ missing CORS标头“ Access-Control-Allow-Origin”丢失-已提供Access-Control-Allow-Origin - CORS header ‘Access-Control-Allow-Origin’ missing - Access-Control-Allow-Origin already given 在CORS预检通道中的CORS标头&#39;Access-Control-Allow-Headers&#39;中缺少令牌&#39;access-control-allow-origin&#39;-react js - missing token ‘access-control-allow-origin’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel - react js yii2 restful api:(原因:缺少 CORS 标头“Access-Control-Allow-Origin”) - yii2 restful api: (Reason: CORS header ‘Access-Control-Allow-Origin’ missing) (原因:缺少 CORS header 'Access-Control-Allow-Origin')。 状态码:204 - (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 204 Nginx CORS&#39;Access-Control-Allow-Origin&#39;标头 - Nginx CORS 'Access-Control-Allow-Origin' header CORS - 没有'Access-Control-Allow-Origin' header 存在于请求的资源上 - CORS - No 'Access-Control-Allow-Origin' header is present on the requested resource React - CORS 问题请求的资源上不存在“Access-Control-Allow-Origin”标头 - React - CORS issue No 'Access-Control-Allow-Origin' header is present on the requested resource 指向托管 Django 服务器的本地 React 应用程序 CORS 没有“访问控制允许来源”header - Local React app pointing to hosted Django server CORS no 'Access-Control-Allow-Origin' header 使用 fetch 与 Express、React、cors、cookies - 'Access-Control-Allow-Origin' header - Using fetch with Express, React, cors, cookies - 'Access-Control-Allow-Origin' header
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM