没有在服务端添加跨源代码如何解决跨源问题?

时间:2019-07-04 08:49:49

标签: java php angular laravel api

不在服务端语言上添加跨源代码。可以解决Java API或Laravel(PHP)的跨源问题angular 7。

无需添加以下代码。

对于Java:

public class CORSFilter extends OncePerRequestFilter {
    private static final Log LOG = LogFactory.getLog(CORSFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        response.addHeader("Access-Control-Allow-Origin", "*");
        if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
            LOG.trace("Sending Header....");
            // CORS "pre-flight" request
            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            // response.addHeader("Access-Control-Allow-Headers", "Authorization");
            response.addHeader("Access-Control-Allow-Headers", "Content-Type");
            response.addHeader("Access-Control-Max-Age", "1");
        }
        filterChain.doFilter(request, response);
    }

}

对于Laravel:

namespace App\Http\Middleware;

use Closure;
class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE');
    }
}

1 个答案:

答案 0 :(得分:1)

来自CORS documentation

  

Web应用程序请求其来源(域,协议和端口)与其自身来源不同的资源时,将执行跨域HTTP请求。

因此,如果您真的不想在API服务器上设置CORS标头,则需要确保API服务器具有与您的角度网站相同的协议,主机和域。

否则,如果仅出于开发/测试目的,则可以尝试使用angular的proxy server