发送后请求时出现CORS错误,但在Spring Boot和Reactjs中未获得请求

时间:2020-08-10 06:26:58

标签: reactjs spring-boot cors

我正在学习Spring Boot并立即做出反应。

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

因此,我在BookResourceImp.java中添加了@CrossOrigin批注。在我观看的教程中,在文件中添加@CrossOrign之后,一切正常。

但是,当我向应用程序发送发布请求时,出现了CROS错误。尽管我的get请求工作正常。

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

非常感谢您。

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");

2 个答案:

答案 0 :(得分:0)

您的@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("/**");
    }
  }
}

答案 1 :(得分:0)

将其添加到您的课程路径上,一切都会好的

    @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 {
        }


    }