简体   繁体   English

当我通过react应用发出请求时,我的网络服务器会发送404,但是当我直接通过chrome或postman访问它时,我的服务器工作正常

[英]My webserver sends 404 when i make the request through react app, but works fine when I access it directly through chrome or postman

My web server is working fine when I call it through chrome. 通过chrome调用时,我的Web服务器工作正常。 However when I am using fetch or axiom in my react-app to call the same url, it returns 404 Not Found. 但是,当我在react-app中使用fetch或axiom调用相同的URL时,它将返回404 Not Found。 The react-app also sends a options request to same url which returns status 200. I have even set this header to allow the origin. react-app还向相同的URL发送一个选项请求,返回状态200。我什至设置了此标头以允许来源。

app.use(async (ctx, next) => {
    var origin = ctx.headers.origin;
    ctx.set({
        'Access-Control-Allow-Headers': 'authorization,Content-Type,refresh',
        'Access-Control-Allow-Methods': "GET,HEAD,POST,PUT,DELETE",
        'Access-Control-Allow-Origin': '*',
        'Connection': 'keep-alive',
        'Access-Control-Allow-Credentials': true
    });
    await next();
    console.log('______________')
  });

require('./routes')(app); //2

my ./routes.js file contain 我的./routes.js文件包含

//router.post('/signin' , signinController.signin);
router.get('/signin' , signinController.signin);

can you please tell me what I am missing here. 你能告诉我我在这里想念的东西吗? My axios call 我的axios电话

axios.get('http://localhost:3002/signin')
              .then(function (response) {
                console.log(response);
              })
              .catch(function (error) {
                console.log(error);
              });

Alright I tried your code out and it works for me if I use app.use(router.allowedMethods()) middleware to pass preflights, OR declare separate option-routes for each route; 好吧,我尝试了您的代码,如果我使用app.use(router.allowedMethods())中间件传递预检信息,或者为每个路由声明单独的选项路由,则对我有用。 Or instead of using router.get() there is router.all('/signin', ...) which will also catch options-requests. 或者不是使用router.get() ,而是router.all('/signin', ...) ,它也会捕获选项请求。

This is my complete server code: 这是我完整的服务器代码:

const app = new Koa();

const router = new Router();

router.get('/signin' , (ctx, next) => {
  ctx.body = '{"status":"hello"}';
});

// Adding a options-route works (instead of router.allowedMethods())
router.options('/signin' , (ctx, next) => {
  ctx.body = '';
});

app.use(async (ctx, next) => {
  var origin = ctx.headers.origin;
  ctx.set({
    'Access-Control-Allow-Headers': 'authorization,Content-Type,refresh',
    'Access-Control-Allow-Methods': "GET,HEAD,POST,PUT,DELETE",
    'Access-Control-Allow-Origin': '*',
    'Connection': 'keep-alive',
    'Access-Control-Allow-Credentials': true
  });
  await next();
  console.log('______________')
});

app.use(router.routes());
// app.use(router.allowedMethods()); // This works instead of separate option-routes.
app.use((ctx, next) => {
  console.log('here');
  next();
});


app.listen(9787);

And this is my call: 这是我的电话:

axios.defaults.headers.common['Authorization'] = "sometoken";
axios.get('http://localhost:9787/signin').then(response =>{
  console.log(response); // {data: {…}, status: 200, ... }
});

(I had to add the header or the CORS won't trigger.) (我必须添加标题,否则CORS将不会触发。)

I've tried setting various origin and headers and it does obey your middleware. 我尝试设置各种来源和标头,但它确实服从您的中间件。 But I did notice that if you choose to use allowedMethods() , that will override your Access-Control-Allow-Methods (and make it useless). 但是我确实注意到,如果您选择使用allowedMethods() ,它将覆盖您的Access-Control-Allow-Methods (并使它无用)。

It has to do with cross origin support 它与跨源支持有关

You can use this package @koa/cors@2 to add cors support 您可以使用此软件包@ koa / cors @ 2添加对cors的支持

const Koa = require('koa');
const cors = require('@koa/cors');

const app = new Koa();
app.use(cors());

Heres the link to the package https://github.com/koajs/cors 这是指向软件包的链接https://github.com/koajs/cors

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 AWS EC2:当我访问网站的 / 时,它工作正常,但是当我直接访问 /signin 时,它返回 NOT FOUND - AWS EC2: When i access the / of the website, it works fine, but when I access directly /signin, it returns NOT FOUND 为什么当我降级node_modules时我的React应用程序可以正常工作,但是更新时却失败了? - Why does my React app works fine when i downgrade node_modules but fails when update it? 当我通过浏览器打开html页面时,为什么倒计时应用程序可以正常运行,但是当我使用http服务器时却不能正常运行? - Why does my countdown app work fine when I open the html page through the browser, but not when I use an http server? GET 请求通过 Axios 返回错误 404,但在 Postman 中有效? - GET request returns Error 404 through Axios, but works in Postman? 当我通过邮递员收到请求时,它没有向我显示数据,但是在书籍中它起作用了 - It doesn't show me the data when I get the request through the postman, but with books it worked Laravel Framework-视频无法通过Laravel显示,当我直接转到文件时可以正常工作 - Laravel Framework - Video not showing through Laravel, works when I go directly to the file 当我尝试通过 map 并在 React 中渲染数据时,应用程序崩溃了 - App crashed when I try to map through and render data in React 当尝试直接访问路线时,React网站/表示未在生产中加载路线,在dev中工作正常 - React website w/ express not loading routes in production when trying to access them directly, works fine in dev 当我在 Chrome 上加载它时,为什么滚动条没有出现在我的反应应用程序中? - Why is scrollbar not appearing in my react app when I load it on chrome? API 通过 Docker 和 Nodejs 请求失败,但在使用 Nodejs 直接访问时工作正常 - API request through Docker & Nodejs fails but works perfectly when accessed directly using the Nodejs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM