Here's some context. I have a ReactJS site, built with Gatsby. This site is entirely static and has no backend. I've recently been working on a backend integration, as I wanted to do some datavis stuff with the GitHub API. Anyway, I was working on building my own backend API with NodeJS, and then proxying the frontend requests (using the fetch API).
The frontend, during development, is at localhost:8000, and the backend at localhost:5000. This is my gatsby-config.js file. It has some other bits unrelated to this question, but the proxy bit is just at the bottom:
module.exports = {
siteMetadata: {
title: "Reece Mercer",
description: "Personal website"
},
plugins: [
'gatsby-plugin-react-helmet',
{
resolve: `gatsby-plugin-manifest`,
options: {
name: 'gatsby-starter-default',
short_name: 'Reece Mercer',
start_url: '/',
background_color: '#663399',
theme_color: '#663399',
display: 'minimal-ui',
icon: 'src/assets/images/website-icon.png', // This path is relative to the root of the site.
},
},
'gatsby-plugin-sass',
'gatsby-plugin-offline',
'gatsby-plugin-favicon',
{
resolve: 'gatsby-source-filesystem',
options: {
path: `${__dirname}/src/blog_posts`,
name: 'blog_posts'
}
},
'gatsby-transformer-remark'
],
proxy: {
prefix: "/myRepoAPI",
url: "http://localhost:5000",
},
}
Essentially, any requests made from the frontend that are to /myRepoAPI/anything should be proxied away from the frontend, to the backend. I've used Postman to validate the backend, and this endpoint functions as it should.
Here is the fetch call I used in a frontend React component:
componentDidMount(){
fetch('/myRepoAPI/hello')
.then(res => console.log(res))
}
Now analysing that console log:
Response {type: "basic", url: "http://localhost:8000/myRepoAPI/hello", redirected: false, status: 200, ok: true, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "basic"
url: "http://localhost:8000/myRepoAPI/hello"
__proto__: Response
The url value is at localhost:8000, not 5000. The proxy hasn't worked. I have tried different combinations of routes, trailing /'s, and even trying the advanced proxy method of developMiddleware. Nothing seems to get it working as it should.
Any help would be much appreciated!
Since Gatsby's internal development server (default at port 8000) handles the proxy, in the response object the url value will always be http://localhost:8000/... regardless whether the proxy's working or not.
You may have more clue when looking at the log from your local server at port 5000, see if the request from Gatsby is actually hitting that end; or log out the actual data you get from the request.
Related
I know there are similar questions out here, but nothing helped me so far. I'm getting a cors error in strapi v4.5.3 although I have configured it to allow the origin. Strapi doesn't seem to take the origins I'm using. My middleware.ts looks like this:
export default [
'strapi::errors',
'strapi::security',
{
name: 'strapi::cors',
config: {
enabled: true,
origin: process.env.CORS_ORIGINS
? process.env.CORS_ORIGINS.split(', ')
: '*',
credentials: true,
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
headers: ['Content-Type', 'Authorization', 'Origin', 'Accept'],
keepHeaderOnError: true,
},
},
'strapi::poweredBy',
'strapi::logger',
'strapi::query',
'strapi::body',
'strapi::session',
'strapi::favicon',
'strapi::public',
]
with the following .env value:
CORS_ORIGINS=http://localhost:1337, http://localhost:6006, http://localhost:18082, https://portal-cms.example.de, https://portal-cms.example.bop
When I'm calling from localhost:6006 or localhost:18082 to localhost:1337 everything works fine. My dev server is available at https://portal-cms.example.de and when I try to call it from localhost:6006 or localhost:18082 I'm getting the following cors error:
Access to XMLHttpRequest at 'https://portal-cms.example.de/api/contact-infos?locale=en' from origin 'http://localhost:6006' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'https://portal-cms.example.bop' that is not equal to the supplied origin.
The request is made via axios from a vue component and looks like this:
console.log(await axios.get('https://portal-cms.example.de/api/contact-infos?locale=en'))
The response header has the value access-control-allow-origin: https://portal-cms.example.bop. I would have expected it to have the value that I configured in my middleware.ts. Am I understanding it wrong? and is there any way to make this error go away?
Here is my vite config
server: {
host: "0.0.0.0",
proxy: {
"/api": {
target: "https://xxx.xxx.inc",
changeOrigin: true,
rewrite: (path) => {
return path.replace(/^\/api/, "");
},
secure: false,
},
},
},
When I post a data, weired things happend!
The POST was "301 Moved Permanently" And it became GET!
vite:proxy /api/core/login -> https://xxx.xxx.inc +0ms
vite:time 475.67ms /core/login +10s
vite:spa-fallback Not rewriting GET /core/login/ because the client prefers JSON. +10s
vite:time 0.73ms /core/login/ +7ms
vite:proxy /api/core/login -> https://xxx.xxx.inc +15m
vite:time 476.08ms /core/login +15m
vite:spa-fallback Not rewriting GET /core/login/ because the client prefers JSON. +15m
vite:time 0.66ms /core/login/ +5ms
For Proxy server,
A POST should be always POST after
I'm at vite config. TS configures the request broker, as follows:
// 开发服务器配置
server: {
host: true,
port: VITE_PORT,
open: VITE_OPEN,
proxy: {
"/MockServer": {
// target: "http://172.16.10.215:32340/",
target: "http://172.18.30.123:8510/gdm-analysis/",
changeOrigin: true,
rewrite: (path) => path.replace(/^\/MockServer/, ""), //替换访问api的url适配服务端
},
},
strictPort: false, //接口被占用时尝试使用下个可用端口,
hmr: true,
},
I start the project locally and visit, and the request is correctly forwarded to http://172.18.30.123:8510/gdm-analysis/,but when I use my colleague's computer to access my local project, the request cannot be forwarded normally, header show:Provisional headers are shown
I am getting isMobile = false in the case of react native app from the express-useragent npm module. Although it is working in the case of Native script app.
Attaching the response from both the apps:
React Native app response:
{
isYaBrowser: false,
isAuthoritative: false,
isMobile: false,
isMobileNative: false,
}
Also the response from Native script app:
{
isYaBrowser: false,
isAuthoritative: true,
isMobile: true,
isMobileNative: true,
}
The code which I've used is as follow:
app.use(useragent.express());
app.get('/', function(req, res){
res.send(req.useragent);
});
I was able to solve this problem from frontend side. In their headers request, they have to send the user-agent explicitly.
‘User-Agent’: Platform.OS == ‘ios’
? ‘AppName/1.6.4.176 CFNetwork/897.15 Darwin/17.5.0’
: ‘AppName/1.6.7.42 Dalvik/2.1.0 (Linux; U; Android 5.1.1; Android SDK built for x86 Build/LMY48X)‘
I am using Vue on Node.js to host my website on an AWS EC2 instance. I dont have an index node.js file, just the vue-router file. I use AWS CloudFront to bind my certificate to my traffic. The problem is that everytime i access the site through the server's link, the site works perfectly, but whenever i access it through the cloud-front link, only the index of the website will show up. No /about or /contact; instead it returns Cannot GET /about.
My Router:
import Vue from 'vue';
import Router from 'vue-router';
import VueCookies from 'vue-cookies';
import Home from './views/Home.vue';
import NotFound from './views/NotFound.vue';
Vue.use(Router);
Vue.use(VueCookies);
VueCookies.config('7d');
VueCookies.set('theme', 'default');
VueCookies.set('unique', Date.now());
VueCookies.set('rwapi-uuid', `v3-${Date.now()}-x9k0`)
export default new Router({
mode: 'history',
routes: [
{ path: '/', name: 'INDEX', component: Home },
{ path: '/about/', name: 'ABOUT', component() { return import('./views/About.vue'); } },
{ path: '/portfolio', name: 'PORTFOLIO', component() { return import('./views/Port.vue'); } },
{ path: '/contact', name: 'CONTACT', component() { return import('./views/Contact.vue'); } },
{ path: '/login', name: 'LOGIN', component() { return import('./views/Login.vue'); } },
{ path: '/404', component: NotFound },
{ path: '*', redirect: '/404' },
],
});
I have already tried to add the historyApiFallback: true to my webpack config but it had no effect.
According to Vue Router's documentation, when using your router in history mode, your webserver requires additional configuration.
I don't exactly know how do EC2 instances work, but if you don't have a webserver proxying all your requests to index.html, Vue-router will not be able to handle the other requests.