我正在创建一个示例应用程序,扩展了 RestfulController 。
我正在连接MySQL数据库,这是我的代码片段
City.groovy
package cityapic
class City {
static constraints = {
name blank:false
pincode blank:false
}
def String name
def String pincode
}
CityController.groovy
package cityapic
import grails.converters.JSON
import grails.rest.RestfulController
class CityController extends RestfulController {
static responseFormats = ['json', 'xml']
def index() {
}
}
UrlMappings.groovy
class UrlMappings {
static mappings = {
"/$controller/$action?/$id?(.$format)?"{ constraints { // apply constraints here
} }
"/"(view:"/index")
"500"(view:'/error')
"/cityAPI/city/"(resource: "city")
}
}
使用此CURL表达式时,它不会对数据库执行POST(保存):
curl -X POST -H "Content-Type: application/json" -H "Cache-Control: no-cache" -H "Postman-Token: 6d436808-017f-7b31-5577-65062417e7ad" -d '{
"name" : "Berhampur",
"pincode": "760001"
}' http://localhost:8080/cityAPIC/city
我知道CURL表达式是正确的。在"存储"中存在一些问题。部分代码。
答案 0 :(得分:1)
将您的网址设置更改为:
"/city"(resource: "city")
或在您的域类中添加注释:
import grails.rest.*
@Resource(uri='/city', formats=["json", "xml"])
class City {
static constraints = {
name blank:false
pincode blank:false
}
def String name
def String pincode
}
资源将是: http://localhost:8080/cityAPIC/city
如果您需要检查所有可以执行的资源:
grails url-mappings-report
此命令将显示所有可用资源。
您可以在grails doc上找到更多信息: grails.github.io/grails-doc/latest/guide/webServices.html#REST
答案 1 :(得分:1)
您需要在CityController上将事务读取更改为false。
@Transactional(readOnly=false)
class CityController extends RestfulController {
因为默认情况下只读取grails.rest.RestfulController类