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>
);
}
}
请参阅下面的产品控制器类服务器端
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) {
...
}
我认为您在使用axios.put
创建请求时遗漏了path变量。要么删除@PathVariable长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) {
...
}
另外,更改@CrossOrigin如下
@CrossOrigin(origins = "http://localhost:3000", methods = {RequestMethod.OPTIONS, RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE}, allowedHeaders = "*", allowCredentials = "true")
你也可以看看这里
我的跨源请求被阻止了: 同源策略不允许从http://localhost:8092/authenticate读取远程资源。(原因:CORS标头'Access-Control-Allow-Origin'丢失)。
我正在尝试将webUntis(文档)API用于学校项目。现在,我只是尝试建立与API的任何类型的连接。 此代码产生以下错误消息: 已阻止跨源请求:同一源策略禁止读取位于的外部资源https://api.webuntis.dk/api/status(原因:缺少CORS标头“访问控制允许来源”)。 这个问题可能如何解决?也许我的API密钥是错误的? 免责声明:错误消息是从德语翻译过来的。
我已经将我的ASP.NET核心web API部署到Azure上,我可以使用Swagger或像Fiddler这样的web调试器访问它的endpoint。在这两种情况下(在Swagger中使用相同的来源,在我的计算机中使用Fiddler使用不同的来源),当访问API时,我会得到预期的结果,在我的中启用CORS如下所示: > 添加到。 使用Fiddler,我可以成功地访问远程API,但没有获得标头。因此
错误:我在Firefox中得到以下内容:外国站点查询被阻止:同源策略不允许读取远程资源http:// localhost:8080 / api / v1 / post /。(原因:“访问控制-允许-源”CORS 标头不存在) 我已经花了几个小时允许CORS与我的Spring Boot服务器通信,以使我的REACT UI与服务器通信。关于堆栈溢出,有许多措辞类似的问题,但建议的解决方案中没有一个解决
我正在开发一个带有jhipster V4.5.6的Spring启动应用程序。但无法配置 CORS。 下面是我的application-dev.yml文件: WebConfigurer.java如下: 和安全配置。java文件如下所示: 现在,我可以使用 GET 请求。但是当我使用POST时,如下所示: 我得到以下错误: XMLHttpRequest 无法加载 http://localhost:80
嗨,我不能禁用CORS在我的项目。我为CORS配置使用了自定义过滤器和Spring Security配置。我见过这个极好的答案:你能在Spring中完全禁用CORS支持吗? 但是当我尝试下面的实现时,我仍然得到CORS错误: CORS配置: