【问题标题】:CORS error when post request is send, but not get request in Spring Boot and Reactjs发送 post 请求时出现 CORS 错误,但在 Spring Boot 和 Reactjs 中未获取请求
【发布时间】:2020-11-29 18:13:37
【问题描述】:

我正在学习spring boot并立即做出反应。

我遇到了 CROS 的问题。在花了一些时间研究这个问题之后,我了解到当恶意访问试图获取存储在缓存中的信息时,它会阻止访问。现在,我的 Web 应用程序将我的 api 请求视为恶意访问。

所以我在 BookResourceImp.java 中添加了@CrossOrigin 注解。在我观看的教程中,在文件中添加@CrossOrign 后,一切正常。

但是,当我向应用程序发送 post 请求时,我收到 CROS 错误。虽然我的获取请求工作正常。

一些解决方案在 java 文件中引入 response.setHeader,如下所示 Spring Boot and CORS 但是由于教程中的那个人只添加了 CrossOrigin 注释,我想知道为什么我的虽然 get request 有效,但它却不起作用。 如果上述链接中的解决方案是最佳选择,请告诉我。

非常感谢您。

Book.js

import React from 'react';

import {Card, Form, Button, Col} from 'react-bootstrap';

import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {faSave, faPlusSquare} from '@fortawesome/free-solid-svg-icons'

import axios from 'axios';

export default class Book extends React.Component {

    constructor(props) {
        super(props);

        this.state = this.initialState;
    }

    initialState = {
        title: '',
        author: '',
        url: '',
        isbn: '',
        price: '',
        lang: '',
    }

    submitBook = e => {
        alert(`${this.state.title}\n ${this.state.author}\n ${this.state.url}\n ${this.state.isbn}\n ${this.state.price}\n ${this.state.lang}\n ${this.state.title}`);
        e.preventDefault();

        const book = {
            title: this.state.title,
            author: this.state.author,
            url: this.state.url,
            isbn: this.state.isbn,
            price: this.state.price,
            lang: this.state.lang
        }

        axios.post("http://localhost:8081/rest/books", book)
            .then(res => {
                console.log("RES", res);
                if (res.data != null) {
                    this.setState(this.initialState);
                    alert("Book saved successfully")
                }
            })
            .catch(err => console.log(err))
    }

    bookChange = e => {
        this.setState({
            [e.target.name]: e.target.value
        });
    }


    render() {

        const {title, author, url, isbn, price, lang} = this.state;

        return (
            <Card className={"border border-dark bg-dark text-white"}>
                <Card.Header><FontAwesomeIcon icon={faSave} className="mr-2"/>Add Book</Card.Header>

                <Form id="bookFromId" onSubmit={this.submitBook}>
                    <Card.Body>
                        <Form.Row>
                            <Form.Group controlId="FormGridTitle" as={Col}>
                                <Form.Label>Title</Form.Label>
                                <Form.Control
                                    type="title"
                                    value={title}
                                    placeholder="Book Titile"
                                    className={"bg-dark text-white"}
                                    name='title'
                                    required
                                    onChange={this.bookChange}
                                />
                            </Form.Group>

                            <Form.Group controlId="formBasicEmail" as={Col}>
                                <Form.Label>Author</Form.Label>
                                <Form.Control
                                    type="text"
                                    value={author}
                                    placeholder="Author"
                                    className={"bg-dark text-white"}
                                    name='author'
                                    onChange={this.bookChange}
                                    required
                                />
                            </Form.Group>
                        </Form.Row>

                        <Form.Row>
                            <Form.Group controlId="formBasicEmail" as={Col}>
                                <Form.Label>Cover Photo URL</Form.Label>
                                <Form.Control
                                    type="text"
                                    value={url}
                                    placeholder="Book Titile"
                                    className={"bg-dark text-white"}
                                    name='url'
                                    onChange={this.bookChange}
                                    required
                                />
                            </Form.Group>

                            <Form.Group controlId="formBasicEmail" as={Col}>
                                <Form.Label>ISBN Number</Form.Label>
                                <Form.Control
                                    type="text"
                                    value={isbn}
                                    placeholder="Author"
                                    className={"bg-dark text-white"}
                                    name='isbn'
                                    onChange={this.bookChange}
                                    required
                                />
                            </Form.Group>
                        </Form.Row>

                        <Form.Row>
                            <Form.Group controlId="formBasicEmail" as={Col}>
                                <Form.Label>Price</Form.Label>
                                <Form.Control
                                    type="text"
                                    value={price}
                                    placeholder="Book Titile"
                                    className={"bg-dark text-white"}
                                    name='price'
                                    onChange={this.bookChange}
                                    required
                                />
                            </Form.Group>

                            <Form.Group controlId="formBasicEmail" as={Col}>
                                <Form.Label>Language</Form.Label>
                                <Form.Control
                                    type="text"
                                    value={lang}
                                    placeholder="Author"
                                    className={"bg-dark text-white"}
                                    name='lang'
                                    onChange={this.bookChange}
                                    required
                                />
                            </Form.Group>
                        </Form.Row>

                    </Card.Body>
                    <Card.Footer style={{"textAlign": "right"}}>
                        <Button size="sm" variant="success" type="submit">
                            <FontAwesomeIcon icon={faPlusSquare} className="mr-2"/>Submit
                        </Button>
                    </Card.Footer>
                </Form>
            </Card>
        );
    }
};

BookResourceImp.java

package com.mightyjava.resource.impl;

import java.util.Collection;
import java.util.Optional;

import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import com.mightyjava.domain.Book;
import com.mightyjava.exception.ApplicationException;
import com.mightyjava.exception.BookNotFoundException;
import com.mightyjava.resource.Resource;
import com.mightyjava.service.IService;

@RestController
@RequestMapping("/books")
@CrossOrigin(origins="http://localhost:3000")
public class BookResourceImpl implements Resource<Book> {
    
    private static Logger log = LoggerFactory.getLogger(BookResourceImpl.class);
    
    @Autowired
    private IService<Book> bookService;

    @Override
    public ResponseEntity<Collection<Book>> findAll() {
        log.info("BookResourceImpl - findAll");

【问题讨论】:

    标签: reactjs spring-boot cors


    【解决方案1】:

    您的 @RequestMapping("/books") 似乎只允许 /books 而您的发布请求是:“http://localhost:8081/rest/books”。

    添加这个 webconfigurer 将为整个应用程序启用 cors:

    package com.codurance.marsroverapi.config;
    
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.CorsRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    @Configuration
    public class WebConfig {
    
      @Configuration
      public class WebConfiguration implements WebMvcConfigurer {
    
        @Override
        public void addCorsMappings(CorsRegistry registry) {
          registry.addMapping("/**");
        }
      }
    }
    

    【讨论】:

    • 您好,感谢您的帮助。我有个问题。我在哪里可以添加此代码?我应该将它添加到 RestController 中还是创建一个文件并添加此代码?我在网上找到的似乎是第一个选项,在RestController中添加代码......
    • 我通常将它添加到配置文件夹中。它是通过注入添加到应用程序中的。
    • 是的,将此类添加到您保存应用程序级配置(如 MVC、安全性、数据库配置)的文件夹中。
    【解决方案2】:

    在你的类路径中添加这个一切都会好的

        @Component
        @Order(Ordered.HIGHEST_PRECEDENCE)
        public class MyCorsFilterConfig implements Filter {
    
            @Override
            public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
                final HttpServletResponse response = (HttpServletResponse) res;
                response.setHeader("Access-Control-Allow-Origin", "*");
                response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
                response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, enctype");
                response.setHeader("Access-Control-Max-Age", "3600");
                if (HttpMethod.OPTIONS.name().equalsIgnoreCase(((HttpServletRequest) req).getMethod())) {
                    response.setStatus(HttpServletResponse.SC_OK);
                } else {
                    chain.doFilter(req, res);
                }
            }
    
            @Override
            public void destroy() {
            }
    
            @Override
            public void init(FilterConfig config) throws ServletException {
            }
    
    
        }
    

    【讨论】:

    • 您好,感谢您的帮助。问题,当您说类路径时,您是指 RestController 吗?或创建一个新文件并添加此代码?
    • 创建一个新文件并将此类添加到您保存应用程序级配置(如 MVC、安全性、数据库配置)的文件夹中
    猜你喜欢
    • 2022-01-06
    • 2022-01-10
    • 2021-06-18
    • 2021-12-21
    • 2012-12-31
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    相关资源
    最近更新 更多