我目前正在努力解决我的 Chrome 开发人员工具控制台中出现的错误
GET http://localhost:8080/movie_db/search/movie?movieTitle=Machete 415 (Unsupported Media Type)
当我尝试使用 Angular JS 连接到我的 REST 服务时。由于我在尝试通过 Chrome 中的简单 REST 插件访问 REST 服务之前遇到了这个问题,我认为很可能缺少 Content-Type 标头参数是原因(应该是 Content-Type: 'application/json ')。
Angular JS 网站说,可以按如下方式设置标头参数:$httpProvider.defaults.headers.get['My-Header']='value'
. 遗憾的是这没有任何影响,问题仍然存在。
因此,我想知道如何使用发送到我的 REST 服务的 Angular JS 来操作标头参数。
目前,我的代码如下所示:
function SearchMovieController($scope, $resource) {
$scope.SearchMovie = $resource('http://localhost\\:8080/movie_db/search/:action',
{action: 'movie', movieTitle: 'Machete'},
{get: {method: 'JSONP', headers: [{'Content-Type': 'application/json'}, {'Accept' : 'application/json'}]}});
$scope.SearchMovie.get()
}
服务器端如下所示(我使用 Spring MVC):
控制器:
@Controller
@RequestMapping( "/search/movie" )
public class SearchController { // TODO rename?
private final TheMovieDBService theMovieDBService;
@Autowired
public SearchController( TheMovieDBService theMovieDBService ) {
this.theMovieDBService = theMovieDBService;
}
@ResponseBody
@RequestMapping( method = RequestMethod.GET, produces = "application/json", consumes = "application/json" )
public Map<String, Object> search( @RequestParam String movieTitle ) {
Map<String, Object> response = new HashMap<String, Object>();
try {
TheMovieDBSearchResult searchResult = theMovieDBService.searchMovie( movieTitle );
response.put( "result", searchResult );
response.put( "success", "true" );
} catch ( EncoderException e ) {
response.put( "success", "false" );
}
return response;
}
}
web.xml
<servlet>
<servlet-name>json</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.u6f6o.apps.movie_db.config.web.ServletConfig</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>json</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>